Main issue is how to test that expected actions were performed once a Promise was completed, for example to test if a component correctly updates its states after receiving some remote content.
In the specs below, the dealWithIt()
simulates a logic performed in response to a completed promise (it updates variable and trigger "another async event").
it('Promises fulfilled by flushMicrotasks',fakeAsync((): void => {
let x = 1;
let y = 2;
let dealWithIt = function(p:Promise<number>) {
p.then( v => {
x = v;
Promise.resolve(v).then( v=> {y = v+1; });
});
};
let p = Promise.resolve(y);
dealWithIt(p);
flushMicrotasks();
//valid if promise handling completed
expect(x).toBe(2);
expect(y).toBe(3);
}));
it('Promises fulfilled by tick',fakeAsync((): void => {
let x = 1;
let y = 2;
let dealWithIt = function(p:Promise<number>) {
p.then( v => {
x = v;
Promise.resolve(v).then( v=> {y = v+1; });
});
};
let p = Promise.resolve(y);
dealWithIt(p);
tick();
//valid if promise handling completed
expect(x).toBe(2);
expect(y).toBe(3);
}));
And both tests pass. At the time of checking expectations the promise was dealt with correctly.
But, is it guaranteed? Or was I just lucky.
Are there any limitations, will all Promises created in the scope of fakeAsync be 'fired' by calling tick
or flushMicrotasks
.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…