Angular 2+,异步测试和setTimeout

时间:2018-06-24 15:56:29

标签: angular unit-testing asynchronous testing

我对测试有疑问。 我使用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承诺只有在所有异步操作都完成后才能解析,并且日志必须为:

### start test
isStable true
>>>>>> COMPONENT TIMEOUT!!!
### end test

我做错了什么?假设必须等待所有异步操作完成到组件中,我应该如何正确编写异步测试?

1 个答案:

答案 0 :(得分:0)

不确定,为什么fixture.whenStable()自己不等待delay (setTimeout)

但是它可以正常返回PromiseObservable返回

但是您可以通过以下两种方法解决它:

方法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 :在规范文件中拥有自己的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)
}));