Back to Angular

Zone.js Testing Utilities

adev/src/content/guide/testing/zone-js-testing-utilities.md

22.0.0-next.104.3 KB
Original Source

Zone.js Testing Utilities

This guide describes testing utilities primarily used for managing and controlling async tasks in unit tests. These utilities are essentially the Zone.js-specific mock clock utilities, particularly relevant for controlling the flow of asynchronous operations within tests.

For general Angular testing utilities, including TestBed and ComponentFixture, see the Testing Utility APIs guide.

Here's a summary of Zone.js-specific functions:

FunctionDetails
waitForAsyncTracks async tasks and completes the tests only once there are no longer any micro or macrotasks remaining in the test zone.
fakeAsyncRuns the body of a test (it) within a special fakeAsync test zone, enabling a linear control flow coding style.
tickSimulates the passage of time and the completion of pending asynchronous activities by flushing both timer and micro-task queues within the fakeAsync test zone. The curious, dedicated reader might enjoy this lengthy blog post, "Tasks, microtasks, queues and schedules". Accepts an optional argument that moves the virtual clock forward by the specified number of milliseconds, clearing asynchronous activities scheduled within that timeframe.
discardPeriodicTasksDiscards any periodic tasks (e.g. setInterval) that were created inside the fakeAsync Zone.
flushMicrotasksWhen a fakeAsync() test ends with pending micro-tasks such as unresolved promises, the test fails with a clear error message.
In general, a test should wait for micro-tasks to finish. When pending microtasks are expected, call flushMicrotasks to flush the micro-task queue and avoid the error.