我在带有业力和茉莉的角度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();
};
});
唯一有效的情况(意味着失败)是最后一个只有“完成”回调的情况。对于第二个,我不确定但是第一个不应该是在角度2中测试异步的正确方法吗?我想用“异步”你在你的功能周围放置一个区域,它正在等待返回的承诺?我试图了解异步实现,但我没有得到它:https://github.com/angular/angular/blob/master/modules/%40angular/core/testing/async.ts
答案 0 :(得分:3)
创建区域inside the async
method。因此,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();
};
}));