angular - Angular/Karma 单元测试错误“1 个计时器仍在队列中”
问题描述
这几乎不是我第一次遇到"1 timer(s) still in the queue"
,但通常我会找到一些方法来使用tick()
ordetectChanges()
等来摆脱它。
下面的测试工作正常,直到我尝试测试我知道应该抛出异常的条件:
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 或未定义视为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 单元测试的帮助时,一个大问题是,即使我明确搜索“业力”,我也大多会找到 Pr0tractor、Pr0tractor 和更多 Pr0tractor 的答案。这不是 Pr0tractor!(故意拼错了一个零,所以它不会得到搜索匹配。)
更新:我可以像这样解决我的问题:
expect(() => {
component.inputComp.case = 'foo';
}).toThrowError(/Invalid camp-input case attribute/);
这不如通过测试组件模板中的 HTML 属性分配(坏)值那么好,因为我只是将值直接强制到属性本身的组件设置器中,但它会一直做到我有更好的解决方案。
解决方案
我遇到了类似的问题。解决方案是使用刷新功能。
import { fakeAsync, flush } from '@angular/core/testing';
it('test something', fakeAsync(() => {
// ...
flush();
}));
推荐阅读
- sql - 有没有办法将列与日期范围相关联?
- javascript - 如何在 child_process spawn() 调用的输出的每一行加上文本前缀?
- excel - 如何获取第 n 个特殊字符右侧的单元格内容
- tinymce - TinyMCE 中独特的自定义格式
- linux - 删除在开始位置和结束位置之间包含特定子字符串的所有行
- vue.js - Vue.js 应用程序在子路径上不返回带有 Nginx Ingress 的脚本(EKS Kubernetes)
- express - 如何在 NestJS 中安装 Express 中间件(express-openapi-validator)?
- mysql - 我无法使用 process.env.variable 连接到 mysql 数据库
- spacy - 为什么 SpaCy 会因为大写字母而改变整个依赖树?
- machine-learning - 非参考损失函数