首页 文章

Angular:在单元测试中从前端检索数据

提问于
浏览
0

我是Angular的新手,并尝试执行某些任务,包括从ts文件中的前端div中检索值 . 方案如下: -

我有两个下拉前端和一个下拉切换按钮 . 插入并选择所需操作后,内容以span / div显示 . 作为单元测试用例的一部分,我需要检查值是否出现在div中 . 另外,为了执行其他操作,我将该值保存在 ***.component.ts file. I have tried several ways to call that array in *** .component.spec.ts(测试用例文件)中的数组中,但无法实现 .

如果有人可以建议可能的解决方案来获得这个决心,那就太好了 .

代码片段

  • 前端
<div class="col">
      <div class="btn-group" dropdown >
        <button type="button" class="btn" (click)="peformSearch(searchOp)" [disabled]="loading">Search </button>
        <button  type="button" dropdownToggle class="btn dropdown-toggle " aria-controls="dropdown-split">

        </button>
        <ul id="dropdown-split" *dropdownMenu class="dropdown-menu"  aria-labelledby="button-split">
          <li role="menuitem"><a class="dropdown-item" >Add</a></li>
          <li role="menuitem"><a class="dropdown-item" >Sub</a></li>
        </ul>
      </div>
    </div>

  </div>
  <div class="form-group row">
      <span class="btn" *ngFor="let e of searchTerms" >{{ e.key }}: {{ e.value }}</span>
  </div>

2 . 测试用例文件(*** . component.spec.ts)

const component = fixture.componentInstance;
component.ngOnInit();
fixture.detectChanges();
const one = component.searchForm.controls['one'];
const two = component.searchForm.controls['two'];              
 // print div or selected value here

2 回答

  • 0
    import { ComponentFixture } from '@angular/core/testing';
    
        let fixture: ComponentFixture<ComponentName>;
    
        beforeEach(() => {
            fixture = TestBed.createComponent(ComponentName);
        })
    
        de = fixture.debugElement.query(By.css('.classname-of-the-tag-whose-value-is-to-be-fetched'));
    
    console.log(de);
    de.textContent on innerHtml should return the required value.
    

    在测试套件里面有各种选项By.css(' . class'),By.id('#id'),By.tagName('div')等

  • 0

    你可以访问像这样的元素

    // print div or selected value here
    const div = fixture.nativeElement.querySelector('div.form-group');
    console.log(div.innerHTML);
    

    为元素提供更具体的css类可能会有所帮助,例如 search-term-list

相关问题