javascript / intermediate
Snippet
Testing Debounced User Search Using fakeAsync and tick
Angular's fakeAsync test zone allows deterministic, synchronous testing of asynchronous operations like debounced input streams and timers. By invoking tick(milliseconds), the virtual test clock advances precisely, simulating asynchronous delay without real-world latency, making assertions against intermediate and final states reliable.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';import { UserSearchComponent } from './user-search.component';import { UserService } from './user.service';import { of } from 'rxjs';describe('UserSearchComponent (fakeAsync)', () => {let component: UserSearchComponent;let fixture: ComponentFixture<UserSearchComponent>;let userServiceSpy: jasmine.SpyObj<UserService>;beforeEach(() => {userServiceSpy = jasmine.createSpyObj('UserService', ['searchUsers']);userServiceSpy.searchUsers.and.returnValue(of([{ id: '1', name: 'Dev User' }]));TestBed.configureTestingModule({imports: [UserSearchComponent],providers: [{ provide: UserService, useValue: userServiceSpy }]});fixture = TestBed.createComponent(UserSearchComponent);component = fixture.componentInstance;});it('triggers search only after debounce time', fakeAsync(() => {component.onSearchInput('developer');expect(userServiceSpy.searchUsers).not.toHaveBeenCalled();tick(300);expect(userServiceSpy.searchUsers).toHaveBeenCalledWith('developer');expect(component.results().length).toBe(1);}));});
angular
Breakdown
1
it('triggers search only after debounce time', fakeAsync(() => {
Wraps the test callback in fakeAsync zone to control timer-based asynchronous code synchronously.
2
expect(userServiceSpy.searchUsers).not.toHaveBeenCalled();
Asserts that the asynchronous search request has not fired prior to the debounce period expiring.
3
tick(300);
Advances the virtual clock by 300 milliseconds to simulate timer completion and flush pending microtasks.