Angular 2+,异步测试和setTimeout

5

我有一个关于测试的问题。

我使用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

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

1个回答

0

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

但是它可以正常处理普通的PromiseObservable返回值。

但你可以通过以下两种方式解决:

方法1:使用tick()手动等待,利用fakeAsync

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');
    });
}));

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接