我有一个关于测试的问题。
我使用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
承诺只有在所有异步操作完成后才会解析,此时必须输出日志:
### start test
isStable true
>>>>>> COMPONENT TIMEOUT!!!
### end test
我做错了什么?如果我必须等待我的组件中所有异步操作都完成,我应该如何正确编写异步测试?