Full answer
Testing time based code with real timers is slow and flaky. fakeAsync helps for promises and timers in Angular tests, but for RxJS pipelines with several operators the TestScheduler gives exact, readable tests.
How it works: new TestScheduler(assertDeepEqual) takes a function that compares actual and expected notifications. In scheduler.run(helpers => { ... }), all RxJS schedulers (timers, debounceTime, delay, interval) use virtual time, so a pipeline that takes seconds runs in microseconds. You describe inputs and expected outputs as marble diagrams.
Marble syntax inside run:
-advances one millisecond. A space is ignored.- A letter or digit is a value emitted at that frame. The value is looked up in the optional values object (
{ a: 'ang', b: 'angular' }). |is completion,#is an error.()groups several events in one frame, such as(ab|).^marks the subscription point of a hot observable, and!marks unsubscription.- Time can be written as a number with unit:
a 299ms b, which is easier than counting dashes.
Helpers: cold('--a|') (starts when subscribed), hot('--a--b') (already running), expectObservable(stream$).toBe('...', values), and expectSubscriptions(source.subscriptions).toBe('^--!') to check that switchMap unsubscribed from the previous inner observable at the right time.
What to test with it: a search pipe (debounce plus distinctUntilChanged plus switchMap), retry with backoff (check the exact delays), polling with takeUntil, and timeouts. In the example, typing "a", "ab" quickly and "abc" later gives only the results for "ab" and "abc", and the earlier request for "a" never runs.
Tips: keep the stream under test in a function that takes its dependencies (the scheduler is global in run, so no injection is needed). Do not mix run with real asynchronous code. For streams inside Angular components, test the pure pipeline function with marbles and keep the component test small.
import assert from 'node:assert';
import { Observable, debounceTime, distinctUntilChanged, map, switchMap, timer } from 'rxjs';
import { TestScheduler } from 'rxjs/testing';
function search(terms$: Observable<string>, delayMs: number): Observable<string> {
return terms$.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((term) => timer(delayMs).pipe(map(() => `results for ${term}`))),
);
}
const scheduler = () => new TestScheduler((actual, expected) => assert.deepStrictEqual(actual, expected));
scheduler().run(({ hot, expectObservable }) => {
const typed = hot('a 100ms b 500ms c 500ms |', { a: 'a', b: 'ab', c: 'abc' });
// "a" is replaced by "ab" within 300 ms, so only "ab" and "abc" reach the server.
expectObservable(search(typed, 50)).toBe('- 450ms x 500ms y 150ms |', {
x: 'results for ab',
y: 'results for abc',
});
});
console.log('search marble test passed');
try {
scheduler().run(({ hot, expectObservable }) => {
const typed = hot('a 400ms |', { a: 'a' });
expectObservable(search(typed, 50)).toBe('- 10ms x |', { x: 'results for a' }); // wrong on purpose
});
} catch {
console.log('wrong expectation was detected');
}RxJS 7.8. The script was run in Node 24 twice with identical output. The marble assertions pass, and a deliberately wrong expectation was also run to confirm that a mismatch throws.
Key points
- `TestScheduler.run` uses virtual time, so time based streams are tested instantly.
- Marbles: `-` 1 ms, letters values, `|` complete, `#` error, `^` and `!` subscribe and unsubscribe.
- Use `cold`, `hot`, `expectObservable` and `expectSubscriptions`.
- Test pipelines as functions. Keep component tests small.
Common mistakes
- Using real timers and `setTimeout` in RxJS tests.
- Forgetting that a `-` is one millisecond inside `run`.
- Mixing real asynchronous code with `run`.
Follow-ups
- How would you check the delays of a retry with backoff?
- When is `fakeAsync` enough?
- What does `expectSubscriptions` verify?
Tips
- Explain virtual time first.
- Draw one marble diagram of a search box.
- Mention subscription checks for `switchMap`.
Evaluation rubric
- Explains virtual time and marble syntax.
- Writes a correct marble test.
- Knows what to test and when to use `fakeAsync`.