must的视图必须显示从组件数据生成的一些复选框(并由(NgModel)有条件地选中和绑定)。
<div *ngFor="let checkableColumn of visibleCatalog">
<label nz-checkbox [(ngModel)]="checkableColumn.checked">
{{ checkableColumn.column.label | titlecase }}
</label>
</div>我知道NgModel更新是异步的,所以我将测试放在fakeAsnyc上下文中,以使测试更简单。
我的第一次尝试是:
it('should update his checkboxes', fakeAsync(() => {
component.ngOnChanges({}); // For populating my data
fixture.detectChanges();
tick();
const checkboxesChecked = document.querySelectorAll('input[type=checkbox]:checked');
expect(checkboxesChecked.length).withContext('1 checkbox should be checked').toBe(1);
}));但是它不起作用,没有选中复选框,我发现下面的复选框是有效的:
it('should update his checkboxes', fakeAsync(() => {
component.ngOnChanges({}); // For populating my data
fixture.detectChanges(); // Added
tick();
fixture.detectChanges();
const checkboxesChecked = document.querySelectorAll('input[type=checkbox]:checked');
expect(checkboxesChecked.length).withContext('1 checkbox should be checked').toBe(1);
}));我不明白为什么我需要在滴答()之前更新我的观点。有人了解这种行为吗?
发布于 2019-10-31 12:29:03
这是一个非常好的,如果棘手的问题。
从关于测试的角度文档看,第一个detectChanges只通过onInit()。为了查看您的异步更改,您需要通过勾选并再次运行,因为要更新的异步进程尚未启动(只有在组件初始化后才启动)。
it('should display error when TwainService fails', fakeAsync(() => {
// tell spy to return an error observable
getQuoteSpy.and.returnValue(
throwError('TwainService test failure'));
fixture.detectChanges(); // onInit()
// sync spy errors immediately after init
tick(); // flush the component's setTimeout()
fixture.detectChanges(); // update errorMessage within setTimeout()
expect(errorMessage()).toMatch(/test failure/, 'should display error');
expect(quoteEl.textContent).toBe('...', 'should show placeholder');
}));对于同步情况角状态,如下所示:
由于间谍结果同步返回,因此getQuote()方法在第一个变化检测周期之后立即更新屏幕上的消息,在此期间角调用ngOnInit。 在测试错误路径时,你就没那么幸运了。虽然服务间谍将同步返回错误,但组件方法调用setTimeout()。测试必须等待至少一次完整的JavaScript引擎,才能获得该值。测试必须是异步的。
https://stackoverflow.com/questions/58642816
复制相似问题