Sub topic 10
Async code and fake timers
This chapter covers components whose behavior depends on time: debouncing, delays, and promises that resolve later. It assumes you can write a basic Vitest test with TestBed, and that you know how to read a ComponentFixture and call detectChanges(). You should also be comfortable with vi.fn() from the previous chapters.
Why time is a problem in tests
A real 300 ms delay makes a test take 300 ms. A test with several delays, or a retry with a 30 second back-off, becomes unusably slow. Real timers also make tests flaky, because a loaded CI machine may fire a timer later than you expect.
Vitest solves this with fake timers. It replaces setTimeout, setInterval, Date, and related functions with versions it controls. Time only moves when your test says so, and it moves instantly.
The subject: a debounced search box
The component below emits the latest typed value 300 ms after the last keystroke. Each call to onInput cancels the pending timer and starts a new one.
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);
}
}Testing with fake timers
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');
});
});Four parts of this test matter:
vi.useFakeTimers()installs the fake clock. Call it before the code under test callssetTimeout. A timer scheduled earlier with the real function stays real and your test cannot advance it.vi.advanceTimersByTime(299)moves the fake clock forward and runs every timer that falls due in that span. Nothing has fired yet, so the spy is untouched.- Advancing by one more millisecond reaches 300 ms, and the callback runs. Testing the boundary on both sides (299 and then 1) proves the delay is exactly 300 ms and not, say, 100 ms.
afterEachcallsvi.useRealTimers(). Without it, the fake clock leaks into later tests in the same file and they hang or fail in confusing ways.
The first call, onInput('a'), was cancelled by clearTimeout and never fires. The assertion toHaveBeenCalledTimes(1) is what proves the debounce works.
Choosing how to move the clock
Vitest offers several ways to advance time. Pick the one that matches what you want to prove.
| Function | What it does | Use it when |
|---|---|---|
| `vi.advanceTimersByTime(ms)` | Moves time forward by `ms` and runs timers due in that span | You care about exact delays |
| `vi.advanceTimersToNextTimer()` | Jumps to the next scheduled timer and runs it | You want to step through timers one by one |
| `vi.runAllTimers()` | Runs every pending timer until none remain | You only care that the work eventually happens |
| `vi.runOnlyPendingTimers()` | Runs the timers pending right now, not ones they schedule | The code uses `setInterval` or reschedules itself |
| `vi.getTimerCount()` | Returns the number of pending timers | You want to check that cleanup cancelled a timer |
Checking that cleanup cancels timers
A common bug is a component that leaves a timer running after it is destroyed. The timer then calls into a dead component. Fake timers let you test this directly with vi.getTimerCount().
Here is a variant of the search box that cancels its timer when destroyed:
import { Component, DestroyRef, inject, output } from '@angular/core';
@Component({ selector: 'app-search-box', template: '' })
export class SearchBoxComponent {
readonly searched = output<string>();
private timer?: ReturnType<typeof setTimeout>;
constructor() {
inject(DestroyRef).onDestroy(() => clearTimeout(this.timer));
}
onInput(value: string) {
clearTimeout(this.timer);
this.timer = setTimeout(() => this.searched.emit(value), 300);
}
}import { TestBed } from '@angular/core/testing';
import { afterEach, describe, it, expect, vi } from 'vitest';
import { SearchBoxComponent } from './search-box.component';
describe('SearchBoxComponent cleanup', () => {
afterEach(() => {
vi.useRealTimers();
});
it('cancels the pending timer when destroyed', () => {
vi.useFakeTimers();
const fixture = TestBed.createComponent(SearchBoxComponent);
const onSearched = vi.fn();
fixture.componentInstance.searched.subscribe(onSearched);
fixture.componentInstance.onInput('late');
expect(vi.getTimerCount()).toBe(1);
fixture.destroy();
expect(vi.getTimerCount()).toBe(0);
vi.advanceTimersByTime(1000);
expect(onSearched).not.toHaveBeenCalled();
});
});Promises and fake timers
Promise callbacks run in the microtask queue, not the timer queue. The synchronous advanceTimersByTime runs timer callbacks, but it does not wait for the promise continuations that those callbacks trigger. When a timer resolves a promise, use the async versions: advanceTimersByTimeAsync, runAllTimersAsync, and runOnlyPendingTimersAsync. They flush microtasks between timers.
import { afterEach, describe, it, expect, vi } from 'vitest';
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
describe('delay', () => {
afterEach(() => {
vi.useRealTimers();
});
it('resolves only after the full time has passed', async () => {
vi.useFakeTimers();
const done = vi.fn();
delay(1000).then(done);
await vi.advanceTimersByTimeAsync(999);
expect(done).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1);
expect(done).toHaveBeenCalledTimes(1);
});
});If you used the synchronous advanceTimersByTime(1) here, the timer would fire and resolve the promise, but the .then(done) continuation would still be waiting in the microtask queue when the assertion ran. The test would fail even though the code is correct. When in doubt about a promise in the chain, use the async variant. It is always safe.
Waiting for real asynchronous work
Not every async test needs fake timers. If a component updates after a promise resolves and no timer is involved, you can wait for the result with vi.waitFor. It calls your callback repeatedly until it stops throwing, or until it times out.
import { Component, signal } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { describe, it, expect, vi } from 'vitest';
@Component({
selector: 'app-greeting',
template: `<p>{{ message() }}</p>`,
})
class GreetingComponent {
protected readonly message = signal('Loading');
constructor() {
Promise.resolve('Hello').then((text) => this.message.set(text));
}
}
describe('GreetingComponent', () => {
it('shows the greeting once the promise resolves', async () => {
const fixture = TestBed.createComponent(GreetingComponent);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('p').textContent).toBe('Loading');
await vi.waitFor(() => {
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('p').textContent).toBe('Hello');
});
});
});Calling fixture.detectChanges() inside the callback is deliberate. Each retry re-renders the template, so the DOM can pick up the new signal value.
fixture.whenStable() is another option. It resolves when Angular has no more tracked pending work, such as in-flight HTTP requests registered with the framework. It does not wait for arbitrary promises or timers you created yourself, and it can wait forever if you have faked the timers it depends on. Prefer vi.waitFor for untracked work, and keep fake timers and whenStable() apart.
Faking the date
vi.useFakeTimers() also replaces Date. Use vi.setSystemTime to pin the clock, so that code showing "today" or computing an expiry is deterministic:
import { afterEach, describe, it, expect, vi } from 'vitest';
describe('Date under fake timers', () => {
afterEach(() => {
vi.useRealTimers();
});
it('reports the time we set', () => {
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-01-15T10:00:00Z'));
expect(new Date().toISOString()).toBe('2026-01-15T10:00:00.000Z');
vi.advanceTimersByTime(60_000);
expect(new Date().toISOString()).toBe('2026-01-15T10:01:00.000Z');
});
});Advancing timers also moves the fake Date forward by the same amount.
Common errors
- The timer never fires. The code scheduled it before
vi.useFakeTimers()ran, for example in a field initializer of a component you created earlier. Install fake timers first, then create the component. - Later tests hang or time out. A test enabled fake timers and never restored them. Put
vi.useRealTimers()inafterEach. - A promise assertion fails although the timer ran. You used the synchronous advance function on a promise chain. Switch to
advanceTimersByTimeAsync. runAllTimersthrows about too many timers. The code has a repeating interval. Advance by a fixed amount instead.- The DOM is stale after time passes. Moving the clock does not re-render. Call
fixture.detectChanges()after you advance, as you do after any other state change.
Exercise
A component calls setTimeout(() => this.saved.emit(), 500) inside a method. Your test calls vi.useFakeTimers(), calls the method, runs vi.advanceTimersByTime(500), and the spy on saved is called. After the test file finishes, other tests in the same file start timing out. What is the most likely cause and the fix?
Show answer
The test never restored real timers, so later tests still run on the fake clock. Add afterEach(() => { vi.useRealTimers(); }) to the file.
Exercise
A service method does await new Promise(r => setTimeout(r, 2000)); this.ready.set(true);. Your test uses fake timers, calls the method without awaiting it, runs vi.advanceTimersByTime(2000), and asserts that ready() is true. The assertion fails. Why, and what should you change?
Show answer
The timer fires and resolves the promise, but the code after the await runs in a microtask that has not been flushed when the assertion runs. Replace the call with await vi.advanceTimersByTimeAsync(2000), which flushes microtasks, and then assert.