首页 > 解决方案 > Angular:在单元测试中从前端检索数据

问题描述

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

我在前端有两个下拉菜单和一个 dropdownToggle 按钮。插入并选择所需的操作后,内容将显示在 span/div 中。作为单元测试用例的一部分,我需要检查值是否出现在 div 中。此外,为了执行其他操作,我将该值保存在*.component.ts 文件的数组中。我尝试了几种方法在 * .component.spec.ts (测试用例文件)中调用该数组,但无法实现。

如果有人可以提出可能的解决方案来解决这个问题,那就太好了。

代码片段

  1. 前端

    <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

标签: javascriptangular

解决方案


you can access the elements like

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

it might be helpful to give more specific css-classes to the elements e.g. search-term-list


推荐阅读