Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use waitForAsync in angular

Tags:

From documentation we can read:

waitForAsync(fn: Function): (done: any) => any

Wraps a test function in an asynchronous test zone. The test will automatically complete when all asynchronous calls within this zone are done. Can be used to wrap an inject call.

I could not understand, when to use waitForAsync function? What's the difference between waitForAsync vs (async or fakeAsync)?

like image 417
Thomas Banderas Avatar asked Oct 16 '20 06:10

Thomas Banderas


People also ask

What is Waitforasync?

waitForAsynclinkWraps a test function in an asynchronous test zone. The test will automatically complete when all asynchronous calls within this zone are done. Can be used to wrap an inject call.

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 is tick () in Angular?

The tick() function simulates the asynchronous passage of time for the timers in the fakeAsync zone in Angular test.

How does fakeAsync work?

Like the async function the fakeAsync function executes the code inside its body in a special fake async test zone. This intercepts and keeps track of all promises created in its body. The tick() function blocks execution and simulates the passage of time until all pending asynchronous activities complete.


Video Answer


2 Answers

In Angular 10.1.0, waitForAsync() has replaced async() to avoid confusion, but is otherwise exactly the same. Any documentation you see that discusses using async() will also apply to waitForAsync(). async() has been marked as deprecated and will be removed entirely in version 12.

like image 55
seairth Avatar answered Sep 18 '22 23:09

seairth


Wraps a test function in an asynchronous test zone. The test will automatically complete when all asynchronous calls within this zone are done. Can be used to wrap an inject call.

So you dont have to manually call done() callback passed as an argument to mark test had finished or use fakeAsync() and other helper functions from '@angular/core/testing'

it('...', waitForAsync(inject([AClass], (object) => {
  object.doSomething.then(() => {
    expect(...);
  })
});

See docs.

like image 24
Felix Avatar answered Sep 16 '22 23:09

Felix