Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular testing: tick vs flushMicrotasks in fakeAsync block

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

like image 214
Glenn Mohammad Avatar asked Sep 16 '18 22:09

Glenn Mohammad


People also ask

What is tick in fakeAsync?

ticklink. Simulates the asynchronous passage of time for the timers in the fakeAsync zone.

What is fakeAsync in angular testing?

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.

What is the difference between async ()' and fakeAsync?

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.

What does flush do in angular testing?

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.


Video Answer


1 Answers

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().

like image 134
Nikhil Doomra Avatar answered Oct 27 '22 03:10

Nikhil Doomra