When to use waitForAsync in angular
Asked Answered
F

2

35

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)?

Ferromagnesian answered 16/10, 2020 at 6:54 Comment(2)
Does this answer your question? What is the difference between fakeAsync and async in angular2 testingLeicester
Hey, sorry but no It's a good point, but the main question is for a waitForAsync method which is not described in article which you postedFerromagnesian
T
43

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.

Tynes answered 5/11, 2020 at 19:24 Comment(1)
The deprecated async() function in Angular's @angular/core/testing library (angular.io/api/core/testing/async) should not be confused with the native async/await in JavaScript and the default testing schematic in modern Angular. So if you see the async/await usage in newly constructed unit tests, this is acceptable and different. One thing is for sure the original async() function had poor naming from Angular and added confusion.Asel
N
8

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.

Numerous answered 10/12, 2020 at 8:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.