Summary:
In most scenarios, fakeAsync()/tick()
can be used interchangeably with async()/whenStable()
. However, the preferred choice is the former unless XHR calls are required, which mandates the use of async()/whenStable()
as fakeAsync()
does not support XHR calls.
Generally, both methods serve similar purposes. The only exception where choosing one over the other is essential is for components with external templates and styles not compiled inline when testing with SystemJS. In such cases, XHR calls prohibit the use of fakeAsync()
, while Webpack allows it due to compiling external resources inline.
Ultimately, the decision between the two comes down to personal preference. When faced with nested asynchronous calls, like in this example, using multiple fixture.whenStable()
calls may result in complex and less readable code.
someAsyncAction();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(something)
changeSomethingElseAsynchronously();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(something);
anotherAsyncAction();
fixture.whenStable().then(() => {
fixture.detectChanges()
expect(somthingeElse)
})
})
})
To enhance readability and maintainability, simplifying the structure without excessive fixture.whenStable()
calls might be preferable.
tick();
fixture.detectChanges();
expect(something)
changeSomethingAsynchronously()
tick();
fixture.detectChanges();
expect(somethingElse)
changeSomethingAsynchronously()
tick();
fixture.detectChanges();
expect(somethingElse);
Considering the need for precision and completeness, following up on fixture.whenStable()
calls becomes crucial to avoid false positives during testing.
fixture.whenStable().then(() => {
expect(...)
console.log('called...')
})
For assurance in test execution and result validation, some developers opt to minimize reliance on async
and lean towards fakeAsync
for its synchronous behavior that ensures all assertions are executed as expected.