Sub topic 10
Async code and fake timers
This chapter assumes you can write a basic Vitest test with TestBed, and that you know how to create a component, call fixture.detectChanges(), and subscribe to an output. Here you will test code that waits, such as a debounce, without making the test wait.
Why real timers are a problem
A component that debounces input waits 300 ms before it emits. A test that waits for real would be slow, and it would be flaky on a busy CI machine. Vitest can replace the global timer functions with fakes. The test then moves the clock forward by hand, so the 300 ms pass instantly and the result is the same on every run.
The component under test
import { Component, output } from '@angular/core';
@Component({ selector: 'app-search-box', template: '' })
export class SearchBoxComponent {
readonly searched = output<string>();
private timer?: ReturnType<typeof setTimeout>;
onInput(value: string) {
clearTimeout(this.timer);
this.timer = setTimeout(() => this.searched.emit(value), 300);
}
}Each call to onInput cancels the pending timer and starts a new one. Only the last value should be emitted.
Writing the test
import { TestBed } from '@angular/core/testing';
import { afterEach, describe, it, expect, vi } from 'vitest';
import { SearchBoxComponent } from './search-box.component';
describe('SearchBoxComponent', () => {
afterEach(() => {
vi.useRealTimers();
});
it('emits only the last value after the delay', () => {
vi.useFakeTimers();
const fixture = TestBed.createComponent(SearchBoxComponent);
const onSearched = vi.fn();
fixture.componentInstance.searched.subscribe(onSearched);
fixture.componentInstance.onInput('a');
fixture.componentInstance.onInput('ab');
vi.advanceTimersByTime(299);
expect(onSearched).not.toHaveBeenCalled();
vi.advanceTimersByTime(1);
expect(onSearched).toHaveBeenCalledTimes(1);
expect(onSearched).toHaveBeenCalledWith('ab');
});
});The test does four things:
vi.useFakeTimers()replacessetTimeout,clearTimeout,setInterval, andDatewith controllable versions. Call it before the code under test schedules anything.- Two quick
onInputcalls simulate typing. The first timer is cancelled. vi.advanceTimersByTime(299)moves the fake clock to just before the deadline. Nothing has fired.- Advancing one more millisecond fires the timer. The boundary check shows the delay is exactly 300 ms, not "roughly".
The afterEach hook calls vi.useRealTimers(). Without it, the fake clock stays installed and can break later tests in the same file.
Other timer helpers
| Helper | What it does |
|---|---|
| `vi.advanceTimersByTime(ms)` | Moves the clock forward and runs timers that come due. |
| `vi.runOnlyPendingTimers()` | Runs the timers scheduled right now, but not ones they schedule. |
| `vi.runAllTimers()` | Runs timers until none remain. Do not use it with an endless `setInterval`. |
| `vi.advanceTimersByTimeAsync(ms)` | Like `advanceTimersByTime`, but also lets pending promise callbacks run between timers. |
Common errors
- Forgetting to restore real timers. Later tests hang or behave oddly. Keep
vi.useRealTimers()inafterEach. - Faking timers after scheduling. A timer created before
vi.useFakeTimers()is a real one, and advancing the fake clock will not fire it. - Expecting promises to follow the fake clock. Promise callbacks are microtasks, which fake timers do not control. If a timer callback awaits something, use the
Asyncvariant, orawait fixture.whenStable()when Angular is the one tracking the pending work. - Not calling
fixture.detectChanges()after a timer fires. If the timer changes a signal that the template reads, the DOM updates only after change detection runs.
Exercise
A test calls vi.useFakeTimers() and then vi.advanceTimersByTime(300), but a debounce that the component scheduled in its constructor never fires. The test creates the component before calling vi.useFakeTimers(). What is wrong, and how do you fix it?
Show answer
The constructor scheduled its timer with the real setTimeout, because the fakes were not installed yet. The fake clock knows nothing about that timer. Call vi.useFakeTimers() before TestBed.createComponent(...), so the constructor uses the fake setTimeout.