这不是我第一次遇到 "1 timer(s) still in the queue"
,但通常我会找到一些方法来使用 tick()
或 detectChanges()
等,以摆脱它。
下面的测试工作正常,直到我尝试测试我知道应该抛出异常的条件:
it('should be able to change case', fakeAsync(() => {
expect(component).toBeTruthy();
fixture.whenStable().then(fakeAsync(() => {
component.case = 'lower';
fixture.autoDetectChanges();
tick(500);
const input = fixture.nativeElement.querySelector('input') as HTMLInputElement;
typeInElement('abcDEF', input);
fixture.autoDetectChanges();
tick(500);
expect(component.text).toEqual('abcdef');
component.case = 'upper';
fixture.autoDetectChanges();
tick(500);
typeInElement('abcDEF', input);
fixture.autoDetectChanges();
tick(500);
expect(component.text).toEqual('ABCDEF');
// Everything above works fine. Here's where the trouble begins
expect(() => {
component.case = 'foo';
fixture.autoDetectChanges();
tick(500);
}).toThrowError(/Invalid case attribute/);
}));
}));
我正在测试的是一个 Angular 组件,它是 Material 输入字段的包装器。该组件有许多可选属性,其中大多数只是常见输入字段功能的传递属性,但也有一些自定义属性,例如我在上面测试的用于大写/小写转换的属性。
case
的可接受值属性是 upper
, lower
, 和 mixed
(空字符串、null 或 undefined 被视为 mixed
)。该组件应该为其他任何事情抛出异常。显然它确实如此,并且测试成功了,但是随着我获得的成功:ERROR: 'Unhandled Promise rejection:', '1 timer(s) still in the queue.', '; Zone:', 'ProxyZone', '; Task:', 'Promise.then', '; Value:', Error: 1 timer(s) still in the queue.
Error: 1 timer(s) still in the queue.
...
谁能告诉我我可能做错了什么,或者是清除挥之不去的计时器的好方法?
免责声明:当我寻求 Karma 单元测试帮助时的一个大问题是,即使我明确搜索“karma”,我也主要找到 Pr0tractor、Pr0tractor 和更多 Pr0tractor 的答案。这不是 Pr0tractor! (故意用零拼错,所以它不会得到搜索匹配。)
更新:我可以像这样解决我的问题:
expect(() => {
component.inputComp.case = 'foo';
}).toThrowError(/Invalid camp-input case attribute/);
这不像通过测试组件模板中的 HTML 属性分配(坏)值那么好,因为我只是将值直接强加到组件的属性本身的 setter 中,但它会一直执行到我有一个更好的解决方案。
最佳答案
我遇到过类似的问题。解决方案是 flush函数用法。
import { fakeAsync, flush } from '@angular/core/testing';
it('test something', fakeAsync(() => {
// ...
flush();
}));
关于Angular/Karma 单元测试错误 "1 timer(s) still in the queue",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58416969/