我正在编写具有*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 Store收到数据时,此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中加载,但是在单位测试中,我无法测试此功能?
我知道我为时已晚,但是有人会在以后阅读。
我遇到了相同的问题,正是由于Angular测试中的错误,它在传递新值ChangeDetectionStrategy
为OnPush
因此,您需要做的是将其覆盖在测试模块中:
TestBed.configureTestingModule({
... your declarations and providers
})
.overrideComponent(ComponentYoureTesting, {
set: { changeDetection: ChangeDetectionStrategy.Default }
})
.compileComponents();
它应该起作用
可能会有所帮助:
it('should search the data with valid client passed from UI', fakeAsync(() => {
// ---
tick();
fixture.detectChanges();
// ---
expect(component.searchData).toHaveBeenCalled();
}));