Test promised Microtasks (code)
Once we handle the concepts of the Micro-Macro task we can cover the testing of this environment in practice:
For micro-tasks we can use as an example the following code:
it('Async test sample - plain promise', fakeAsync(() => {
let test: boolean;
console.log('Regular synchronous call');
Promise
.resolve()
.then(() => {
console.log('1st promise called');
test = true;
return Promise.resolve();
})
.then(() => {
console.log('2nd promise called');
});
console.log('Running test assertions');
flushMicrotasks();
expect(test).toBeTruthy(true);
}));
For macro-tasks we can use as an example the following code:
it('Async test example - setTimeout() with flush()', fakeAsync(() => {
let test = false;
setTimeout(() => { });
setTimeout(() => {
test = true;
expect(test).toBeTruthy();
}, 1000);
flush();
}));
Now we could cover both scenarios, using the micro-macro tasks:
it('Async test example - Promises & setTimeout()', fakeAsync(() => {
let counter = 0;
Promise.resolve()
.then(() => {
counter += 10;
setTimeout(() => {
counter += 1;
}, 1000);
});
expect(counter).toBe(0);
flushMicrotasks();
expect(counter).toBe(10);
tick(500);
expect(counter).toBe(10);
tick(500);
expect(counter).toBe(11);
}));
Last updated
Was this helpful?