【发布时间】:2018-12-03 07:50:20
【问题描述】:
我有一个关于测试的问题。 我使用 Angular 6、karma 和 jasmine。
我的测试是:
it(`my test`, async(() => {
console.log('### start test');
fixture.detectChanges();
// call a method which has async code
fixture.componentInstance.fakeTimeout();
console.log('isStable', fixture.isStable());
fixture.whenStable().then(() => {
// here I must check smth only when all async operations are completed
console.log('### end test');
});
}));
我尝试以不同的方式实现fakeTimeout 方法,即:
public fakeTimeout() {
new Promise((resolve, reject) => {
setTimeout(() => {
console.log('>>>>>> COMPONENT TIMEOUT!!!');
resolve(true);
}, 2000);
}).then(() => {});
}
或
public fakeTimeout() {
setTimeout(() => {
console.log('>>>>>> COMPONENT TIMEOUT!!!');
}, 2000);
}
在这两种情况下,我都有以下日志:
### start test
isStable true
### end test
>>>>>> COMPONENT TIMEOUT!!!
但是,根据官方文档,whenStable promise 只有在所有异步操作完成后才会解析,并且日志必须是:
### start test
isStable true
>>>>>> COMPONENT TIMEOUT!!!
### end test
我做错了什么?如果我必须等待对组件的所有异步操作完成,我应该如何正确编写异步测试?
【问题讨论】:
标签: angular unit-testing asynchronous testing