Angular2 async unit testing with jasmine
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Angular provides three utilities for testing asynchronous code with Jasmine: fakeAsync/tick (simulates time passage synchronously), waitForAsync (wraps the test in an async zone), and done callback (Jasmine's native async support). The most common and recommended approach is fakeAsync with tick because it gives you precise control over when async operations complete, making tests deterministic. For HTTP calls, use HttpClientTestingModule to mock requests and flush responses on demand.
fakeAsync and tick (Recommended)
fakeAsync creates a synchronous test zone where all async operations (setTimeout, setInterval, Promises) are queued but not executed until you call tick(ms). This eliminates race conditions and flaky tests.
waitForAsync (formerly async)
waitForAsync waits for all async operations in the Angular zone to complete before the test finishes. It is useful when you cannot easily control timing with tick.
Jasmine done Callback
Jasmine's done callback is framework-agnostic. Call done() when the async operation completes. If you forget to call it, the test times out after 5 seconds (configurable with jasmine.DEFAULT_TIMEOUT_INTERVAL).
Testing Observable Streams
Testing with async/await
Native async/await works for simple Promise-based tests. For tests involving Angular zones, timers, or HTTP, prefer fakeAsync.
Testing Timers (setInterval)
discardPeriodicTasks() prevents the "periodic timers still in queue" error when the test ends with active intervals.
Common Pitfalls
- Forgetting
tick()infakeAsync: Withouttick(), setTimeout and Promise callbacks never execute. The test passes with stale values, hiding bugs. Alwaystick()the appropriate duration after triggering async operations. - Not calling
fixture.detectChanges(): Angular does not automatically run change detection in tests. After async data arrives, callfixture.detectChanges()to update the DOM before asserting on rendered content. - Periodic tasks left in queue: If your component uses
setIntervalor RxJSinterval, calldiscardPeriodicTasks()at the end offakeAsynctests, or unsubscribe/clear the interval. Otherwise, Angular throws "periodic timer(s) still in the queue." - Mixing
fakeAsyncwith real async: You cannot use realsetTimeoutorfetchinsidefakeAsync— it intercepts them. If you need real HTTP calls (integration tests), usewaitForAsyncordoneinstead. httpMock.verify()missing: WithoutafterEach(() => httpMock.verify()), unexpected HTTP requests silently pass. Always verify that no unmatched requests remain after each test.
Summary
- Use
fakeAsync+tick()for most async tests — it gives deterministic control over timing - Use
waitForAsyncwhen you need Angular zone-aware async completion without manual tick control - Use Jasmine's
donecallback for simple Promise-based tests outside Angular - Always call
fixture.detectChanges()after async data arrives to update the template - Use
HttpClientTestingModuleto mock HTTP requests andhttpMock.verify()to catch unexpected calls - Call
discardPeriodicTasks()to clean up timers infakeAsynctests
Related reading
- Angular 2, async testing and setTimeout
- Angular 2 routing with fragments, async data
- Angular Async Validator on multiple form fields
- Angular Custom Async Validator stays in pending state
- Angular 2 spring boot server side events
- Angular 6 - Could not find module @angular-devkit/build-angular
- Angular with Jasmine is there a conflict between async in beforeEach and async in it?
- App does not contain the correct beta entitlement
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.