As far as my understanding goes from reading the Angular testing docs, calling tick()
flushes both (supported) macro tasks, and micro-task queues within the fakeAsync
block. In which case, under the hood, I assume, calling tick()
will be the same as having some additional calls + calling flushMicrotasks()
.
Question is, is there any case where I should use:
it('should pass', fakeAsync(() => {
// given some setup...
doSomethingAsynchronous();
flushMicrotasks();
// do some assertions...
}));
instead of
it('should pass', fakeAsync(() => {
// given some setup...
doSomethingAsynchronous();
tick();
// do some assertions...
}));
❓
ticklink. Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
fakeAsynclinkWraps a function to be executed in the fakeAsync zone: Microtasks are manually executed by calling flushMicrotasks() . Timers are synchronous; tick() simulates the asynchronous passage of time.
tl;dr. In almost all cases, they can be used interchangeably, but using fakeAsync()/tick() combo is preferred unless you need to make an XHR call, in which case you MUST use async()/whenStable() combo, as fakeAsync() does not support XHR calls. For the most part they can be used interchangeably.
and for flush: Simulates the asynchronous passage of time for the timers in the fakeAsync zone by draining the macrotask queue until it is empty. The returned value is the milliseconds of time that would have been elapsed.
Excerpt from the article here.
macrotasks are enqueued by setTimeout, setInterval, setImmediate, etc. microtasks by process.nextTick, Promises, MutationObserver, etc.
So if you are using setTimeouts, setInterval etc then use tick() and if you are using some promises, then you can use either tick() or flushMicrotasks().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With