This project contains systematic examples for the blog article Angular: Asynchronous Testing Recipe.
The code under test is contained in the following components:
Each of these components has the following functions:
immediate()
: Returns an asynchronous object (corresponding to the component's name) that is executed immediately.delayed()
: Returns an asynchronous object (corresponding to the component's name) that is executed after a delay of 1 second (via setTimeout()).indirectImmediate()
: Invokesimmediate()
, and sets the componentsvalue
variable to the resolved value.indirectDelayed()
: Invokesimmediate()
, and sets the componentsvalue
variable to the resolved value.
The tests invoke these methods and assert the results using different mechanisms. Some of the tests fail because not all mechanisms are suitable for testing each kind of asynchronous code. Also beware that some tests seem to pass, but only because the contained assertions are not executed while the test is running.
The following tables provide an overview of the tests and their outcomes for each type of component. Abbreviations used:
- n/a: not applicable
- n/n: not necessary
Since the async
function declaration provides syntactic sugar for Promise handling, the tests and results for both components are identical.
Test | immediate() | delayed() | indirectImmediate() | indirectDelayed() |
---|---|---|---|---|
basic | ✗ | ✗ | ✗ | ✗ |
async / await | ✓ | ✓ | n/a | n/a |
callback | ✓ | ✓ | ✗ | ✗ |
waitForAsync | ✓ | ✓ | ✗ | ✗ |
+ whenStable | n/n | n/n | ✓ | ✓ |
+ await whenStable | n/n | n/n | ✓ | ✓ |
fakeAsync | ✓ | ✓ | ✗ | ✗ |
+ tick() | n/n | n/n | ✓ | ✗ |
+ tick(...) | n/n | n/n | ✓ | ✓ |
+ flush | n/n | n/n | ✓ | ✓ |
+ flushMicrotasks | n/n | n/n | ✓ | ✗ |
Test | immediate() | delayed() | indirectImmediate() | indirectDelayed() |
---|---|---|---|---|
basic | ✓ | ✗ | ✓ | ✗ |
callback | ✓ | ✓ | ✓ | ✗ |
waitForAsync | ✓ | ✓ | ✓ | ✗ |
+ whenStable | n/n | n/n | n/n | ✓ |
+ await whenStable | n/n | n/n | n/n | ✓ |
fakeAsync | ✓ | ✓ | ✓ | ✗ |
+ tick() | n/n | n/n | n/n | ✗ |
+ tick(...) | n/n | n/n | n/n | ✓ |
+ flush | n/n | n/n | n/n | ✗ |
+ flushMicrotasks | n/n | n/n | n/n | ✗ |
Test | immediate() | delayed() | indirectImmediate() | indirectDelayed() |
---|---|---|---|---|
basic | ✓ | ✗ | ✓ | ✗ |
callback | ✓ | ✗ | ✓ | ✗ |
waitForAsync | ✓ | ✗ | ✓ | ✗ |
+ whenStable | n/n | ✓ | n/n | ✓ |
+ await whenStable | n/n | ✓ | n/n | ✓ |
fakeAsync | ✓ | ✗ | ✓ | ✗ |
+ tick() | n/n | ✗ | n/n | ✗ |
+ tick(...) | n/n | ✓ | n/n | ✓ |
+ flush | n/n | ✓ | n/n | ✓ |
+ flushMicrotasks | n/n | ✗ | n/n | ✗ |