我有一个关于测试的问题.
我使用Angular 6,业力和茉莉.
我使用Angular 6,业力和茉莉.
我的测试是:
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
我做错了什么?如果必须等待所有异步操作完成到我的组件中,我应该如何正确编写异步测试?
解决方法
不确定,为什么fixture.whenStable()不会自己等待延迟(setTimeout).
但它可以正常使用Promise或Observable返回
但你可以解决它的方式:
方法1:您可以使用tick()手动等待使用fakeAync
it(`my test`,fakeAsync(() => { console.log('### start test'); fixture.detectChanges(); // call a method which has async code fixture.componentInstance.fakeTimeout(); tick(2100); // just more than the delay mentioned inside the component. console.log('isStable',fixture.isStable()); fixture.whenStable().then(() => { // here I must check smth only when all async operations are completed console.log('### end test'); }); }));
方法2:在spec文件中有自己的setTimeout并使用done()完成测试
it(`my test`,((done) => { console.log('### start test'); fixture.detectChanges(); // call a method which has async code fixture.componentInstance.fakeTimeout(); setTimeout(()=> { console.log('isStable',fixture.isStable()); console.log('### end test'); done(); },2100) }));