Nim*_*oel 6 typescript karma-jasmine ngrx angular angular-test
我正在为有条件的 html div 编写单元测试*ngIf。
<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>
Run Code Online (Sandbox Code Playgroud)
当我从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));
});
}
Run Code Online (Sandbox Code Playgroud)
现在,在为此编写单元测试用例时。
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();
}));
Run Code Online (Sandbox Code Playgroud)
问题是,在控制台中,在调用该函数之前,我得到的长度为 0,在调用该函数之后,我得到的长度也为 0。当我们从商店收到数据时,它应该是 1。正是因为这个 *ngif 条件,*ngIf="clientSearchResults$ | async as searchResults"
数据正在 DIV 中加载,但是在单元测试中我仍然无法测试这个东西?
我知道我\xe2\x80\x99m 太晚了,但将来可能会有人读到它。
\n\n我遇到了同样的问题,这是因为 Angular 测试中的错误,如果组件是,则在将新值传递给输入时,它不会\xe2\x80\x99t 触发更改ChangeDetectionStrategy检测OnPush
所以你需要做的是在测试模块中覆盖它:
\n\nTestBed.configureTestingModule({\n ... your declarations and providers\n})\n.overrideComponent(ComponentYoureTesting, {\n set: { changeDetection: ChangeDetectionStrategy.Default }\n})\n.compileComponents();\nRun Code Online (Sandbox Code Playgroud)\n\n它应该有效
\n也许这可以帮助:
it('should search the data with valid client passed from UI', fakeAsync(() => {
// ---
tick();
fixture.detectChanges();
// ---
expect(component.searchData).toHaveBeenCalled();
}));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4931 次 |
| 最近记录: |