Angular异步无法解决超时



@angular/core/testing中的Angular's async似乎也无法在使用asyncasync时解决测试中的超时。 不幸的是,我无法在任何形式的plunkr或jsfiddle上复制此错误。

重新创建的最简单方法是简单创建一个新的Angular CLI应用程序并将此代码粘贴到App.component.spec.ts:

import { async } from "@angular/core/testing";
describe("test async", () => {
   let count: number = 0;
   beforeEach(async(() => {
       count++;
       console.log('async before test ' + count);
       setTimeout(() => {
           console.log('timeout before test ' + count);
       }, 1000);
   }))
   it("async test 1", async(() => {
       console.log('starting test 1');
       setTimeout(() => {
           console.log('test 1 finished');
           console.log('expected count: 1, actual count: ' + count);
           expect(count).toBe(1, "should be test 1");
       }, 2000);
   }));
   it("async test 2", async(() => {
       console.log('starting test 2');
       setTimeout(() => {
           console.log('test 2 finished');
           console.log('expected count: 2, actual count: ' + count);
           expect(count).toBe(2, "should be test 2");
       }, 2000);
   }));
   it("async test 3", async(() => {
       console.log('starting test 3');
       setTimeout(() => {
           console.log('test 3 finished');
           console.log('expected count: 3, actual count: ' + count);
           expect(count).toBe(3, "should be test 3");
       }, 2000);
   }));
});

如果您运行此测试,则应看到输出如下:

async before test 1
timeout before test 1
starting test 1
async before test 2
timeout before test 2
starting test 2
async before test 3
test 1 finished
expected count: 1, actual count: 3
timeout before test 3
starting test 3
test 2 finished
expected count: 2, actual count: 3
test 3 finished
expected count: 3, actual count: 3

,但从我的理解中这是不正确的,因为测试中的超时应该在下一次测试开始之前完成,这是异步的全部。

这是输出正常工作的样子:

async before test 1
timeout before test 1
starting test 1
test 1 finished
expected count: 1, actual count: 1
async before test 2
timeout before test 2
starting test 2
test 2 finished
expected count: 2, actual count: 2
async before test 3
timeout before test 3
starting test 3
test 3 finished
expected count: 3, actual count: 3

任何帮助将不胜感激,谢谢!

编写本文时,它是一个有角的错误。我发现了2张门票,证实了这一点:#16647和#12115

来自 @angular/core/Testing的异步不是在与异步的情况下使用异步的测试中解决超时的时间

async仅解决承诺不是setTimeout。您可以将settimeout包装在延迟功能

const delay = (ms) => new Promise(res => setTimeout(res,ms));

最新更新