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