使用角度2茉莉花中的ngif异步调用单元测试html元素

时间:2018-04-01 11:24:09

标签: angular typescript karma-jasmine ngrx angular-test

我正在为具有*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中的数据正在加载,但是在单元测试中我仍然无法测试这个东西吗?

2 个答案:

答案 0 :(得分:0)

这可能会有所帮助:

it('should search the data with valid client passed from UI', fakeAsync(() => {
  // ---
  tick();
  fixture.detectChanges();
  // --- 
  expect(component.searchData).toHaveBeenCalled();
}));

答案 1 :(得分:0)

我知道我来晚了,但是将来有人会读。

我遇到了同样的问题,这是由于Angular测试中的错误,如果组件ChangeDetectionStrategyOnPush的情况下将新值传递给输入时,它不会触发更改检测

因此,您需要做的是在“测试”模块中覆盖它:

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

它应该可以工作

相关问题