Testing RxJS with Marble Diagrams
Marble diagrams make the timing of asynchronous streams visible. With TestScheduler.run and virtual time, you test RxJS operators deterministically: no real waiting, no flakiness.
A test for debounceTime(2000) against the real clock takes two seconds. Twenty such tests take forty seconds – and despite all that waiting, they fail sporadically as soon as the machine is under load. This is the math reactive test suites fail on: setTimeout, done callbacks, a framework that waits for each test case. The suite gets slow, it gets flaky, and at some point nobody dares to take it seriously anymore.
The TestScheduler computes instead. Inside run(), a virtual clock runs in which one frame equals exactly one millisecond, and the complete timing of a stream is written as a short string: '-a-b-c|'. Two seconds of waiting become microseconds of compute time. How this marble syntax works, how you test real operators with TestScheduler.run and where the typical pitfalls are – that’s what this article is about, based on RxJS 7 throughout.
Why time is the real problem#
An observable is a value over time – or more precisely: a sequence of emissions spread across a timeline, finished by a complete or aborted by an error. With synchronous values, testing is trivial: subscribe, collect the values in an array, compare. But the interesting part of RxJS is precisely the time-based part. When does a debounceTime fire? Does a throttleTime swallow the right values? Does the complete come before or after the last emission?
As soon as you test this with real time, you have three problems at once. The test really takes as long as the timing dictates. It’s nondeterministic, because the real clock simply doesn’t tick with millisecond precision. And it forces you into asynchronous test code with done callbacks, where one forgotten call makes the test hang silently until the timeout kicks in.
Marble testing turns this logic around. Instead of real time, a virtual clock runs that the TestScheduler controls. Time isn’t waited for, it’s computed. And the flow isn’t described in imperative code but as a diagram.
The marble syntax#
A marble diagram is a string in which every character has a meaning on the timeline. Time runs from left to right, and every symbol stands either for time passing or for an event in the stream. This is the entire reference:
-– one time frame, meaning one tick of the virtual clock. Insiderun(), one frame equals exactly 1 ms.a–z(or any other character) – anextemission. The concrete value is mapped through avaluesobject, such as{ a: 1, b: 2 }.|– thecompletesignal; the stream ends normally.#– anerror; the stream ends with an error.()– synchronous grouping: several notifications in the same frame, for example(ab|).^– the subscription point forhot, the so-called zero frame. Frames before it count as negative.!– the unsubscription point, relevant in subscription diagrams.<n>ms/<n>s/<n>m– shorthand for many frames, such as10msinstead of ten hyphens.
A detail that is easy to overlook: spaces don’t create a frame. They only serve visual alignment and are ignored. So you can write the input and the expected output one below the other and align them neatly with spaces without changing the timing – only - and the actual symbols count.
The string '-a-b-c|' therefore reads like this: one frame of silence, then value a, one frame, value b, one frame, value c, immediately followed by complete. Six frames in total, three values, a clean completion. This readability is exactly the point – you see the timing without having to reconstruct it from imperative code.
cold and hot#
Before we write tests, you need the distinction between cold and hot, because it determines when time starts to run.
A cold observable only starts when someone subscribes. The timeline begins at the moment of subscription. That’s the typical behavior for HTTP requests or other data sources that start anew for each subscriber. A hot observable, on the other hand, is already running, independent of subscriptions – like a DOM event or a Subject that is already firing while you aren’t even listening yet. Here, the ^ marks the moment the tested subscription joins; everything before it has already happened and lies in the negative frame range.
If you want to read up on the four Subject types and their multicast behavior again, I covered them in detail in The Four Subject Types in RxJS – hot marbles model exactly this “already running” behavior.
The first test: map with virtual time#
Let’s start with the simplest meaningful case: a map operator. We want to show that every incoming value is multiplied by ten and that timing and completion are passed through unchanged.
First, setting up the TestScheduler. The constructor receives an assertion function that wraps the deep equality of your test framework – here using Jest as an example, but Jasmine or Vitest work the same way:
import { TestScheduler } from 'rxjs/testing';
import { map, debounceTime } from 'rxjs/operators';
let testScheduler: TestScheduler;
beforeEach(() => {
testScheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
});
The actual test then runs entirely inside testScheduler.run. The callback receives a helpers object from which we pull cold and expectObservable:
test('map multiplies each value by ten', () => {
testScheduler.run(({ cold, expectObservable }) => {
const source$ = cold('-a-b-c|', { a: 1, b: 2, c: 3 });
const result$ = source$.pipe(map((x) => x * 10));
expectObservable(result$).toBe('-a-b-c|', { a: 10, b: 20, c: 30 });
});
});
The pattern you see here repeats in every marble test: actual stream against expected diagram. The input is a cold observable with a diagram and a values object. The operator pipeline hangs off it. And expectObservable(...).toBe(...) describes what should come out. The output timing is identical to the input timing, because map doesn’t change anything about time – only the value mapping in the second object is different.
Why does this work without real waiting? Because run() automatically runs through the virtual time when it returns – internally through a flush that you usually don’t have to call yourself. The whole flow has been processed synchronously as soon as the callback ends.
The real payoff: debounceTime#
With map, you don’t really notice the advantage yet. It becomes obvious the moment a time-based operator comes into play. debounceTime(n) only passes a value on when n frames of silence follow it – if a new value arrives before that, the old one is discarded. That’s exactly the kind of behavior that becomes torture with real time and a finger exercise with virtual time.
The key point: inside the run() callback, every time-based operator is automatically redirected to the TestScheduler. You don’t have to pass the scheduler to debounceTime manually. delay, debounceTime, throttleTime, interval, timer – they all use the virtual clock as soon as they run inside run().
test('debounceTime keeps only the last value after a quiet window', () => {
testScheduler.run(({ hot, expectObservable }) => {
// frame: 0 5 10
const source$ = hot('-a--b--c---|');
const result$ = source$.pipe(debounceTime(3));
// a is displaced by b, b by c; only c survives the 3-frame quiet window
expectObservable(result$).toBe('----------c|');
});
});
Let’s work through it, because this is exactly where most mistakes happen. a arrives at frame 1, so its debounce window would expire at frame 4. But that’s exactly when b arrives and displaces a before its emission is triggered. For b, the window starts over and would end at frame 7 – that’s where c arrives, same game, b drops out too. After c at frame 7, there is finally enough quiet: the window expires at frame 10, and the complete follows at frame 11. So only c remains, shifted back by three frames. The expected diagram models exactly this shift.
This arithmetic isn’t a side show; it’s the core. If your expected marble is off by even one frame, the deep equality check fails. That’s annoying at first and quickly becomes a strength: the test forces you to really understand the timing instead of guessing it.
What happens in a frame#
The following diagram shows the flow for the map case as three parallel timelines – input at the top, operator in the middle, output at the bottom. This is the fastest way to see that map transforms the values but leaves the timing untouched.
flowchart TB
subgraph IN["input$ – cold('-a-b-c|')"]
direction LR
i0["-"] --> i1["a=1"] --> i2["-"] --> i3["b=2"] --> i4["-"] --> i5["c=3"] --> i6["|"]
end
subgraph OP["operator"]
direction LR
op["map(x => x * 10)<br/>same frames,<br/>new values"]
end
subgraph OUT["output$ – '-a-b-c|'"]
direction LR
o0["-"] --> o1["a=10"] --> o2["-"] --> o3["b=20"] --> o4["-"] --> o5["c=30"] --> o6["|"]
end
IN --> OP --> OUTEach box is a frame. The values travel from top to bottom through the operator, and the timing is preserved frame by frame. With a time-based operator like debounceTime, the bottom timeline would shift relative to the top one and drop values – exactly what we just worked through.
Checking subscription timing#
Sometimes it isn’t enough to know which values come out – you want to know when and for how long a subscription existed at all. For this, cold and hot provide a .subscriptions property that you can check against a diagram of its own. expectSubscriptions uses ^ for the subscribe moment and ! for the unsubscribe moment:
test('records subscription and unsubscription frames', () => {
testScheduler.run(({ cold, expectObservable, expectSubscriptions }) => {
const source$ = cold('-a-b-c|');
const subscription = '^-----!';
expectObservable(source$).toBe('-a-b-c|');
expectSubscriptions(source$.subscriptions).toBe(subscription);
});
});
This is especially valuable when you test operators like switchMap or takeUntil, where the real effect is that an inner subscription is canceled at the right moment. The value stream then often looks unspectacular – the truth lies in the subscription diagram.
The three pitfalls#
The same three sources of errors keep coming up in code reviews. They are behind most “Why is my test red?” moments.
First: real time instead of virtual time. The automatic redirection of time-based operators applies exclusively inside the run() callback. If you build your observable outside of it or fall back on the old style, where you pass the scheduler manually, the real clock suddenly runs again. The test becomes slow and flaky, and the whole gain is gone. Everything that has timing belongs in the run() callback.
Second: frame counting. debounceTime(20) inside run() means 20 frames, that is, 20 ms. Your expected diagram has to model this delay exactly – whether with 20 hyphens or with 20ms. An off-by-one in frame counting is by far the most common reason for a failing marble test. Take the time to really work out the timing instead of estimating it.
Third: whitespace is deceptive. Spaces don’t create a frame; they only align things visually. When you align input and expected output, make sure both are frame-synchronous – and that values firing synchronously in the same frame are grouped with (). An (ab|) is something completely different from ab|, even though it looks almost the same.
The old style for contrast#
For context, a word about history, because you will come across older code online. In the past, you used the TestScheduler without run(), passed the scheduler explicitly to the operators and called testScheduler.flush() manually at the end. In this legacy style, one frame also equaled 10 ms instead of 1 ms. In principle, that still works, but it’s more error-prone and more cumbersome.
The recommended way is clearly testScheduler.run(helpers => …) with the clear rule: one frame equals 1 ms, automatic redirection of all time-based operators, automatic flush at the end. So if you see testScheduler.flush() or a manually passed scheduler argument somewhere, that’s a sign of old code – not a pattern you should follow.
Conclusion#
Marble testing solves the one problem that makes reactive programming hard to test: time. Instead of waiting for it, you make it visible and computable. A short string describes the complete timing of a stream, the TestScheduler verifies it in virtual time, and your suite stays fast and deterministic – no done callbacks, no timeouts, no sporadic failures.
Getting started takes some practice, especially with counting frames. But once that sinks in, you won’t want to go back. A debounceTime test that used to run for two seconds and was occasionally red now runs in microseconds and is reliable. And on top of that, the expected diagram documents the behavior so clearly that it replaces half the docs. Start small – a map, a debounceTime – and work through every timing deliberately. If you then use reactive streams on the server side too, you’ll find the right follow-up in RxJS in Node.js.
Further reading#
- Testing RxJS Code with Marble Diagrams – the official guide to marble syntax and
TestScheduler.run. - TestScheduler API – the complete API reference with all helper signatures.
Revised and translated from German with the help of AI.