Sub topic 16
Testing Streams with TestScheduler and Marble Diagrams
This chapter assumes you know pipe, map, and the flattening operators from earlier chapters, and that your project already runs unit tests with Jasmine or Jest. Testing streams with real timers is slow and flaky. RxJS solves this with TestScheduler, which runs streams on virtual time and describes the emissions you expect as text strings called marble diagrams.
The Working Model
A marble diagram is a string where each character stands for an event on a timeline. Inside scheduler.run(), one character is one virtual millisecond, called a frame.
| Symbol | Meaning | Column |
|---|---|---|
| `-` | One frame passes with no emission | |
| `a`, `b`, ... | A value is emitted (looked up in the values object) | |
| `\ | ` | The stream completes |
| `#` | The stream errors | |
| `(ab)` | Values emitted together in the same frame | |
| `100ms` | Time progression: 100 virtual milliseconds pass | |
| spaces | Ignored, so you can use them to line up diagrams |
cold() creates an observable that starts its timeline when subscribed. expectObservable() subscribes to the stream under test and records what it emits. The scheduler then passes the actual and expected recordings to your assertion function.
A Basic 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 the expected diagram are labels. The values object maps them to the actual data, so a means 1 in the source and 2 in the result.
Testing Time-Based Operators
Within run(), operators such as debounceTime, delay, and interval use virtual time on their own. A 300 ms debounce finishes instantly.
import { TestScheduler } from 'rxjs/testing';
import { debounceTime } from 'rxjs';
describe('debounced input', () => {
it('emits only after 300ms of silence', () => {
const scheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
scheduler.run(({ cold, expectObservable }) => {
const source$ = cold('a 100ms b 400ms c|');
const result$ = source$.pipe(debounceTime(300));
expectObservable(result$).toBe('401ms b 101ms (c|)');
});
});
});Here is the timing. a arrives at frame 0 and b at frame 101, so b replaces a before 300 ms pass. b is emitted at 101 + 300 = 401. c arrives at frame 502, and the source completes at 503. On completion, debounceTime emits the pending c right away, so c and the completion share frame 503.
Testing Errors
Use # to simulate a failure. The third argument to cold() sets the error value.
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: 1 }, new Error('boom'));
const result$ = source$.pipe(catchError(() => of(0)));
expectObservable(result$).toBe('-a-(b|)', { a: 1, b: 0 });
});
});
});Common Errors
- Treating each character as free time. Every value character takes a frame, and so does each group in parentheses. After
(c|), the clock has moved forward. - Leaving out spaces around time progressions. Write
a 100ms b, nota100msb. - Creating observables outside
run(). Streams built outside the callback use real schedulers, and the test hangs or fails. - Testing real
HttpClientcalls with marbles. Swap the HTTP call for acold()observable, or useHttpTestingControllerto test the request itself.
Exercise
A source is cold('-a-b-c-|', { a: 1, b: 2, c: 3 }) piped through filter(x => x % 2 === 1). What marble string and values object should expectObservable(...).toBe() receive?
Show answer
'-a---c-|' with { a: 1, c: 3 }. The value 2 is filtered out, but its frame still passes, so a dash takes its place and the timing of later events stays the same.
Exercise
Why does the debounceTime test finish instantly instead of waiting about half a second?
Show answer
Inside scheduler.run(), RxJS replaces the default schedulers with the TestScheduler's virtual clock. Time-based operators read virtual frames, and the scheduler moves through them synchronously without real timers.