Sub topic 16
Testing Streams with TestScheduler and Marble Diagrams
This chapter assumes you already know pipe, basic operators, the flattening operators from the switchMap chapter, and the debounced search pattern. It also assumes you can run a Jest or Jasmine spec in an Angular project. The examples use Jest-style expect(...).toEqual(...), which also works in Jasmine.
Testing an observable with real timers is slow and flaky. A test for debounceTime(300) would have to wait 300 real milliseconds, and the result would depend on how busy the machine is. The RxJS TestScheduler fixes this. It runs your stream on virtual time, a simulated clock that jumps forward instantly. You describe the input and the expected output as marble diagrams, which are short strings that draw values on a timeline.
The Working Model
A TestScheduler takes one argument: an assertion function. It calls that function with the actual emissions and the expected emissions, both turned into plain arrays of frame-stamped notifications. You choose how to compare them, which is usually with a deep equality check.
Inside scheduler.run(callback), three things happen:
- You build test observables from marble strings with
coldorhot. - You apply the operators under test.
- You register expectations with
expectObservableandexpectSubscriptions.
When the callback returns, the scheduler flushes. It runs the virtual clock to the end, records every notification, and calls your assertion function. You never call flush() yourself in run mode.
Here is the smallest useful test:
import { TestScheduler } from 'rxjs/testing';
import { map } from 'rxjs';
describe('doubling stream', () => {
it('doubles each value', () => {
const scheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
scheduler.run(({ cold, expectObservable }) => {
const source$ = cold('-a-b-|', { a: 1, b: 2 });
const result$ = source$.pipe(map(x => x * 2));
expectObservable(result$).toBe('-a-b-|', { a: 2, b: 4 });
});
});
});The letters in a marble string are placeholders. The second argument maps each letter to a real value. If you leave the map out, the letter itself becomes the emitted string value.
Marble Syntax Reference
Each character occupies one frame. In run mode, one frame is one virtual millisecond.
| Symbol | Meaning | Column |
|---|---|---|
| `-` | One frame passes with no emission | |
| `a` to `z`, digits | A value emitted in that frame | |
| `\ | ` | Completion |
| `#` | Error (the third argument to `cold`/`hot`/`toBe` sets the error value) | |
| `(ab)` | Group: `a` and `b` emit in the same frame | |
| `^` | Subscription point (hot observables and subscription marbles) | |
| `!` | Unsubscription point (subscription marbles) | |
| `100ms`, `2s` | Time progression: advance that much virtual time | |
| space | Ignored, for alignment and readability |
Time progressions need spaces around them: 'a 100ms b'. Without the spaces, the parser reads 100ms as separate value characters.
Cold vs Hot Test Observables
cold(marbles) creates an observable that starts its timeline when something subscribes to it. Each subscriber gets its own timeline. This matches HttpClient observables and most of what you will mock.
hot(marbles) creates an observable whose timeline starts at frame 0 no matter who subscribes. A ^ marks where the test subscribes. Values before ^ are already gone. Use hot to model DOM events, valueChanges, or a Subject that emits whether or not anyone listens.
Both test observables record their subscriptions in a subscriptions property. That lets you assert when an operator subscribed and unsubscribed, which matters for flattening operators.
Asserting Cancellation in switchMap
This test checks that switchMap cancels the first inner request when a new outer value arrives. The same cold inner$ serves both inner subscriptions, and each gets a fresh timeline.
import { TestScheduler } from 'rxjs/testing';
import { switchMap } from 'rxjs';
describe('switchMap', () => {
it('cancels the previous inner observable', () => {
const scheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
scheduler.run(({ cold, hot, expectObservable, expectSubscriptions }) => {
const source$ = hot('-a---b------|');
const inner$ = cold('--x--y|');
const result$ = source$.pipe(switchMap(() => inner$));
expectObservable(result$).toBe('---x---x--y-|');
expectSubscriptions(inner$.subscriptions).toBe([
'-^---!',
'-----^-----!',
]);
});
});
});The frames work out like this:
aarrives at frame 1, so the first inner subscription starts at 1. Itsxemits at 3. Itsywould emit at 6.barrives at frame 5.switchMapunsubscribes the first inner subscription (!at 5), so itsynever appears.- The second inner subscription starts at 5. Its
xemits at 7,yat 10, and it completes at 11. - The outer completes at 12.
switchMapcompletes once the outer and the active inner have both completed.
The subscription marbles prove the cancellation. The output marble alone could not tell you whether the first request was still running in the background.
Testing Time-Based Operators Without Waiting
In run mode, TestScheduler patches the default async scheduler. Operators such as debounceTime, delay, throttleTime, and interval then run on virtual time with no code changes. A 300 ms debounce costs nothing to test.
To test the debounced search from the forms chapter, pull the stream logic out of the component into a pure function. The function takes the input stream and the search function as parameters, so the test can pass marbles instead of a FormControl and HttpClient.
// search-results.ts
import { Observable, debounceTime, distinctUntilChanged, filter, switchMap } from 'rxjs';
export function searchResults(
terms$: Observable<string>,
search: (term: string) => Observable<string[]>
): Observable<string[]> {
return terms$.pipe(
debounceTime(300),
distinctUntilChanged(),
filter(term => term.length >= 2),
switchMap(search)
);
}// search-results.spec.ts
import { TestScheduler } from 'rxjs/testing';
import { searchResults } from './search-results';
describe('searchResults', () => {
it('debounces, filters short terms, and searches the settled term', () => {
const scheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
scheduler.run(({ cold, expectObservable }) => {
const terms$ = cold('a 100ms b 400ms c 499ms |', {
a: 'an',
b: 'ang',
c: 'x',
});
const search = (term: string) => cold('--r|', { r: [term] });
expectObservable(searchResults(terms$, search)).toBe(
'403ms r 598ms |',
{ r: ['ang'] }
);
});
});
});Here is the timeline:
'an'arrives at frame 0 and'ang'at frame 101. The second value restarts the debounce timer, so'an'is dropped.'ang'settles at frame 401 (101 + 300). The fake search subscribes then and emitsrtwo frames later, at 403.'x'arrives at 502 and settles at 802. The length filter drops it, so no search runs.- The source completes at 1002, and the result completes in the same frame: 403 + 1 + 598 = 1002.
The component then becomes a thin wrapper: results$ = searchResults(this.query.valueChanges, term => this.http.get<string[]>('/api/search', { params: { q: term } })).
Testing Errors and Recovery
The # symbol emits an error. Pass the error value as the third argument, or leave it out to get the default string 'error'.
import { TestScheduler } from 'rxjs/testing';
import { catchError, of } from 'rxjs';
describe('fallback on error', () => {
it('replaces an error with a fallback value', () => {
const scheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
scheduler.run(({ cold, expectObservable }) => {
const source$ = cold('-a-#', { a: 'data' }, new Error('boom'));
const result$ = source$.pipe(catchError(() => of('fallback')));
expectObservable(result$).toBe('-a-(f|)', { a: 'data', f: 'fallback' });
});
});
});of('fallback') emits and completes synchronously, so the value and the completion share frame 3. The group (f|) expresses that.
Common Errors and Gotchas
| Symptom | Cause | Fix |
|---|---|---|
| Expected marble is off by a few frames | Groups take up frames for their parentheses | Count `(`, `)`, and contents as frames, or put a time progression after the group |
| Test hangs or times out | Code under test uses Promises, `setTimeout`, or `fetch` directly | Virtual time only covers RxJS schedulers. Wrap async work in observables, or mock it with `cold` |
| `100ms` shows up as values `1`, `0`, `0` | No spaces around the time progression | Write `'a 100ms b'` |
| Emissions land at frame 0 when you expected later | Used `hot` without `^`, or `hot` where `cold` was meant | Decide whether the source exists before subscription; use `^` to place it |
| Frame numbers ten times larger than expected | Test runs outside `run()`, where each character is 10 virtual units | Always use `scheduler.run` |
| Test passes but never asserts | `expectObservable` called after the callback, or a new scheduler per assertion | Register every expectation inside the `run` callback |
| HttpClient test ignores marbles | `HttpTestingController` responds on `flush()`, not on virtual time | Test stream logic as a pure function with a `cold` fake, and test HTTP wiring separately |
Decision Criteria: When to Use Marble Tests
Use marble tests when correctness depends on timing or ordering: debouncing, throttling, flattening strategy, retry with delay, combineLatest emission rules, or cancellation. Use plain subscribe-and-collect tests for synchronous transformations like a single map, where a marble string adds notation without catching more bugs. For BehaviorSubject state services, call the service methods and read the observable with firstValueFrom or a collected array. Bring in marbles only when the service adds time-based operators.
Exercise
In the switchMap test, replace switchMap with mergeMap and keep the same source$ ('-a---b------|') and inner$ ('--x--y|'). What is the expected output marble?
Show answer
'---x--yx--y-|'. mergeMap keeps the first inner subscription alive, so its y emits at frame 6. The second inner emits x at 7 and y at 10. The result completes at 12, when the outer completes, because both inners are finished by then (frames 7 and 11).
Exercise
In the searchResults test, change c from 'x' to 'angu'. What is the new expected output marble, and why does the result no longer complete at frame 1002?
Show answer
'403ms r 400ms s 1ms |' with r: ['ang'] and s: ['angu']. 'angu' arrives at 502, settles at 802, passes the filter, and the second search emits at 804. The outer completes at 1002, but switchMap keeps going while an inner is active. The second inner completes at 805, and the outer is already complete from 1002 on, so the result completes at 1002. Frames: r at 403, then 404 + 400 = 804 for s, then 805 + 1ms = 806 is wrong, so correct the tail: after s at 804, time is 805; the completion is at 1002, which needs 197ms. The correct marble is '403ms r 400ms s 197ms |'.
Exercise
A teammate writes cold('-(ab)-c|') and expects c at frame 3. At which frame does c actually emit, and when does the observable complete?
Show answer
c emits at frame 6 and the observable completes at frame 7. The '-' is frame 0, a and b both emit at frame 1, the group's five characters take up frames 1 through 5, the next '-' is frame 6... more precisely, the characters '(ab)' span frames 1–4, the '-' is frame 5, c is frame 6, and '|' is frame 7.