Angular 2+,异步测试和setTimeout

Dol*_*ios 5 testing unit-testing asynchronous angular

我有一个关于测试的问题.我使用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');
    });
}));
Run Code Online (Sandbox Code Playgroud)

我试图以fakeTimeout不同的方式实现该方法,即:

public fakeTimeout() {
    new Promise((resolve, reject) => {
        setTimeout(() => {
            console.log('>>>>>> COMPONENT TIMEOUT!!!');
            resolve(true);
        }, 2000);
    }).then(() => {});
}
Run Code Online (Sandbox Code Playgroud)

要么

public fakeTimeout() {
    setTimeout(() => {
        console.log('>>>>>> COMPONENT TIMEOUT!!!');
    }, 2000);
}
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,我都有以下日志:

### start test
isStable true
### end test
>>>>>> COMPONENT TIMEOUT!!!
Run Code Online (Sandbox Code Playgroud)

但是,根据官方文档,whenStablepromise只会解析所有异步操作,并且日志必须是:

### start test
isStable true
>>>>>> COMPONENT TIMEOUT!!!
### end test
Run Code Online (Sandbox Code Playgroud)

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

Ami*_*ani 0

不确定,为什么不自己fixture.whenStable()等待。delay (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');
    });
}));
Run Code Online (Sandbox Code Playgroud)

方法 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)
}));
Run Code Online (Sandbox Code Playgroud)