dimanche 24 juin 2018

Angular 2+, async testing and setTimeout

I have a question about testing. I use Angular 6, karma and jasmine.

My test is:

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

I've tried to implement the fakeTimeout method in different ways, namely:

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

or

public fakeTimeout() {
    setTimeout(() => {
        console.log('>>>>>> COMPONENT TIMEOUT!!!');
    }, 2000);
}

In both cases I had a following log:

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

But, according to the official documentation, whenStable promise resolves only then all async operations are completed, and a log must be:

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

What did I do wrong? How should I write an async test correctly, provided that I must wait for a completion of all async operations into my component?

Aucun commentaire:

Enregistrer un commentaire