Angular 2测试:异步测试的正确方法是什么?

Angular 2 Testing: What's the correct way for async testing?

本文关键字:测试 方法 是什么 异步 Angular      更新时间:2023-09-26

我在一个有karma和jasmine的angular 2项目中做了以下测试:

let a: any;
beforeEach(() => {
    a = {};
    setTimeout(() => {
        a.test();
    }, 1000);
});
it('should work with async and promise', async(() => {
   return new Promise((resolve) => {
       a.test = () => {
           console.log('erster test');
           assertThat(true, is(false));
           resolve();
       };
   });
}));
it('should work with async and done', async((done) => {
    a.test = () => {
        console.log('zweiter test');
        assertThat(true, is(false));
        done();
    };
}));
it('should work with done', (done) => {
    a.test = () => {
        console.log('dritter test');
        assertThat(true, is(false));
        done();
    };
});

唯一有效的情况(意味着它失败)是最后一个只有"done"回调的情况。第二个我不确定,但第一个不应该是正确的方式来测试异步在angular 2?我认为与"async"你放置一个区域周围的功能,它正在等待返回的承诺?我试图使异步实现的意义,但我没有得到它:https://github.com/angular/angular/blob/master/modules/%40angular/core/testing/async.ts

async方法中创建区域。所以你的setTimeout(在beforeEach中)不在那个区域内。如果您将setTimeout移动到 async回调中的,那么它就在该区域中,并且测试应该按预期工作(意味着等待异步任务完成)。

it('should work with async and promise', async(() => {
  setTimeout(() => {
    a.test();
  }, 1000);
  return new Promise((resolve) => {
    a.test = () => {
      console.log('erster test');
      expect(true).toBe(false);
      resolve();
    };
  });
}));
it('should work with async and done', async((done: Function) => {
  setTimeout(() => {
    a.test();
  }, 1000);
  a.test = () => {
    console.log('zweiter test');
    expect(true).toBe(false);
    done();
  };
}));