如何解决角度测试为什么在单击时需要刷新但在triggerEventHandler中不需要刷新
我有一个Angular模块,其中包含列表,卡片,详细信息和编辑组件。
列表模板如下所示:
<own-list>
<button [routerLink]="['/','mod','create']" data-testid="new-request">Create</button>
<own-card *ngFor="let elem of elements" [routerLink]="['/',elem.id]"></own-card>
<own-list>
在测试时,单击卡时会转到其详细信息页面:
test('it should navigate to detail when clicking a card',fakeAsync(() => {
const cardElems = rootFixture.debugElement.queryAll(By.css('own-card'));
// Navigate to top card detail
cardElems[0].nativeElement.click();
tick();
fixture.detectChanges();
// Check route is correct
expect(location.path()).toBe(`/mod/${sortedElements[0].id}`);
}));
工作正常。
在测试单击“创建”按钮时可以进行编辑时:
test('it should navigate to edit when clicking new request',fakeAsync(() => {
const debugCreateBtn = rootFixture.debugElement.query(By.css(`[data-testid="new-request"]`));
// Navigate to edit
debugCreateBtn.nativeElement.click();
tick();
fixture.detectChanges();
// Check route is correct
expect(location.path()).toBe(`/mod/create`);
}));
失败并显示1 periodic timer(s) still in the queue
。
如果我这样添加flush
:
test('it should navigate to edit when clicking new request',fakeAsync(() => {
const debugCreateBtn = rootFixture.debugElement.query(By.css(`[data-testid="new-request"]`));
// Navigate to edit
debugCreateBtn.nativeElement.click();
tick();
fixture.detectChanges();
flush(); // <-- new flush
// Check route is correct
expect(location.path()).toBe(`/mod/create`);
}));
效果很好。
如果我切换到triggerEventHandler
:
test('it should navigate to edit when clicking new request',fakeAsync(() => {
const debugCreateBtn = rootFixture.debugElement.query(By.css(`[data-testid="new-request"]`));
// Navigate to edit
// Run in ngZone to avoid warning
fixture.ngZone.run(() => debugCreateBtn.triggerEventHandler('click',{ button: 0 }));
tick();
fixture.detectChanges();
// Check route is correct
expect(location.path()).toBe(`/mod/create`);
}));
然后它可以正常工作,而无需冲洗。
有人可以解释为什么在每种情况下都行不通吗?
解决方法
flushMicrotasks刷新未决的微任务,滴答刷新未决的微任务和进展时间,刷新刷新未决的微任务,宏任务和进展时间,所有这些都是在fakeAsync的上下文中进行的。
诸如click之类的本地事件是宏任务。未将异步设置为true的triggerEventHandler和EventEmitters使用微任务。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。