5

我正在为*ngIf有条件的 html div 编写单元测试。

<div *ngIf="clientSearchResults$ | async  as searchResults" class = 'fgf'  #datalist id="mydata" >
  <app-client-list id="clientDataTable1" class="clientDataTable dataTable" [clients]='searchResults'></app-client-list>
</div>

当我从ngrx商店收到数据时,这个ngIf条件就成立了。下面是填充此数据的组件代码。

searchData(client: Client) {
      //// some conditions
      this._clientService.getClientList()
     .subscribe(data => {
      const filteredData = this.filterData(data, client);
      this.isDataFound = filteredData !== null && filteredData.length > 0;
      this.testbool = true;
      /// In this line, my div got the data and using async condition, we 
      /// fill the div element.
      this.store.dispatch(new SetClientSearchResultsAction(filteredData));

    });
}

现在,在为此编写单元测试用例时。

it('should search the data with valid client passed from UI', async(() => {
    let debugFixture: DebugElement = fixture.debugElement;
    let htmlElement: HTMLElement = debugFixture.nativeElement;
    let clientListGrid = htmlElement.getElementsByClassName('fgf');
    let testbool= htmlElement.getElementsByClassName('testbool');

    spyOn(component, 'searchData').and.callThrough();
    spyOn(component, 'filterData').and.returnValue(CLIENT_OBJECT);
    spyOn(clientService, 'getClientList').and.callThrough();

    console.log("=========before======="+ clientListGrid.length);

    component.searchData(validClient);
    component.clientSearchResults$ = store.select('searchResults');
    fixture.detectChanges();
    debugFixture = fixture.debugElement;
    htmlElement = debugFixture.nativeElement;
    clientListGrid = htmlElement.getElementsByClassName('fgf');

    console.log("=========after ======="+ clientListGrid.length);

    expect(component.searchData).toHaveBeenCalled();
  }));

问题是,在控制台中,在调用函数之前,我得到的长度为 0,在调用函数之后,我得到的长度也为 0。它应该是 1,当我们从商店收到数据时。正是因为这个 *ngif 条件,*ngIf="clientSearchResults$ | async as searchResults"

数据在 DIV 中加载,但在单元测试中我仍然无法测试这个东西?

4

2 回答 2

3

我知道我为时已晚,但将来有人可能会读到它。

ChangeDetectionStrategy我遇到了同样的问题,这是因为 Angular 测试中的错误,如果组件是,当将新值传递给输入时,它不会触发更改检测OnPush

所以你需要做的是在测试模块中覆盖它:

TestBed.configureTestingModule({
  ... your declarations and providers
})
.overrideComponent(ComponentYoureTesting, {
  set: { changeDetection: ChangeDetectionStrategy.Default }
})
.compileComponents();

它应该工作

于 2019-07-29T12:39:35.887 回答
2

可能这会有所帮助:

it('should search the data with valid client passed from UI', fakeAsync(() => {
  // ---
  tick();
  fixture.detectChanges();
  // --- 
  expect(component.searchData).toHaveBeenCalled();
}));
于 2018-04-01T22:53:35.640 回答