首页 > 解决方案 > 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属性的可接受值为upperlowermixed(将空字符串、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 属性分配(坏)值那么好,因为我只是将值直接强制到属性本身的组件设置器中,但它会一直做到我有更好的解决方案。

标签: angulartypescriptunit-testingkarma-jasmine

解决方案


我遇到了类似的问题。解决方案是使用刷新功能。

import { fakeAsync, flush } from '@angular/core/testing';

it('test something', fakeAsync(() => {

  // ...

  flush();
}));

推荐阅读