| | |

RxJS 16 ๐ŸŸฃ Marble Testing & Debugging โ€” Writing deterministic async tests with TestScheduler and marble diagrams

โฑ๏ธ Estimated read: 10 min | |

Testing asynchronous code is notoriously difficult because of non-determinism. A test that relies on setTimeout or real-world network responses is subject to the fluctuations of the event loop, thread scheduling, and machine performance. These tests are often slow, flaky, and hard to debug. In RxJS, we solve this with Virtual Time. Marble testing allows you to write tests that execute synchronously, consuming zero wall-clock time, by mocking the progression of time entirely. You define the input timeline, specify the operator under test, and assert the expected output timeline.

This chapter covers the anatomy of the TestScheduler, the domain-specific language (DSL) of marble diagrams, and the assertion helper methods. We start by explaining the run() environment, which is the standard wrapper for modern RxJS tests. Then, we dive into the marble syntax, covering time frames, emissions, errors, and completions. We conclude by exploring how to debug failing marble tests and how to use marble diagrams to visualize complex streams before you even write the code.

Key point: Marble testing replaces wall-clock time with virtual time, allowing you to assert the exact timing of emissions, errors, and completions using a precise, readable DSL that executes synchronously and deterministically.


Why Marble Testing exists

The non-determinism problem. Standard async tests rely on await, done() callbacks, or real timers. If a CI server is under heavy load, a 100ms timeout might take 150ms to fire, causing a “flaky” test that passes locally but fails randomly in production. Virtual time eliminates this by making the clock a variable you control.

The readability problem. Without marbles, testing an operator like debounceTime(300) requires setting up a real timer, waiting, emitting, waiting again, and asserting. This bloats test files with setup boilerplate. A marble string like "-a---b---|" is a compact, visual representation of the entire lifecycle.

The “Time-Travel” capability. You cannot easily test what happens in the middle of a switchMap chain with standard unit tests without significant mocking. With marbles, you can represent the outer and inner streams simultaneously, making it possible to assert exactly when inner subscriptions occur.

Synchronous execution. Because marble tests run in a virtual environment, they are instantaneous. You can run hundreds of complex async tests in milliseconds. This encourages developers to write more tests for edge cases, like race conditions or rapid-fire events, which are usually skipped due to test overhead.

Visual documentation. Marble diagrams serve as the definitive specification of a stream’s behavior. If a new developer needs to understand how an operator transforms a sequence, they can read the marble diagram as a visual contract, often more quickly than reading the imperative implementation.


a. The TestScheduler and the run() environment

The TestScheduler is the engine behind marble testing. It keeps track of the virtual clock and dispatches scheduled work. While you can instantiate it manually, the run() method is the recommended way to use it in modern RxJS (v7+). run() automatically handles the setup and teardown, and it manages the injection of virtual time schedulers into the operators.

import { TestScheduler } from 'rxjs/testing';

// The helper is the object provided by the run function
const testScheduler = new TestScheduler((actual, expected) => {
  expect(actual).toEqual(expected);
});

testScheduler.run(({ cold, hot, expectObservable }) => {
  // Marble tests live here
});

When you are inside run(), the TestScheduler intercepts calls to asyncScheduler, asapScheduler, and animationFrameScheduler and routes them to the virtual clock. This means you do not need to pass schedulers into operators manually; the TestScheduler forces them into virtual mode automatically.

b. The Marble DSL

Marble diagrams are strings where each character represents a unit of time (a “frame”). By default, one frame equals 10 milliseconds, though this can be configured.

  • – (dash): A passage of time (1 frame).
  • a – z, 0 – 9, A – Z: Emitted values.
  • | (pipe): Completion of the stream.
  • # (hash): An error notification.
  • () (parentheses): Grouping multiple events into the same frame.
// A stream that emits '1' at frame 1, '2' at frame 2, and completes at frame 3
const source = cold('-1-2-|');

// A stream that emits 'x' and 'y' in the same frame (synchronously)
const sync = cold('-(xy)-|');

The string -a--b---| means:

  1. Frame 0: (nothing)
  2. Frame 1: Emit ‘a’
  3. Frame 2: (nothing)
  4. Frame 3: (nothing)
  5. Frame 4: Emit ‘b’
  6. Frame 5, 6, 7: (nothing)
  7. Frame 8: Completion

c. Assertion methods

expectObservable is the primary assertion method. It subscribes to your observable, records the emissions, and compares them against the expected marble string.

testScheduler.run(({ cold, expectObservable }) => {
  const source = cold('-a---|');
  const expected =    '-a---|';

  const result = source.pipe(map(v => v));

  expectObservable(result).toBe(expected);
});

expectSubscriptions is the counterpart. It allows you to assert when the observable was subscribed to and when it was unsubscribed. This is crucial for verifying cancellation logic, such as ensuring switchMap unsubscribes from the previous inner observable.

const source = cold('-a---|');
const subs =        '^----!'; // Subscribed at frame 1, unsubscribed at frame 5

expectSubscriptions(source.subscriptions).toBe(subs);

d. Debugging Marble Tests

When a marble test fails, the output can be cryptic. It usually displays the actual object stream versus the expected marble diagram. Because the error messages often show the timestamp-value pairs, you must correlate them back to your marble string.

If expectObservable fails, check the “actual” timeline versus the “expected” timeline. A common issue is an off-by-one error (an emission arriving one frame too late/early). Always double-check your marble string spacing.

To debug, you can log inside the operator chain before the test assertion. While you cannot use console.log inside a marble string, you can add tap to your pipeline and use the test helper’s time:

source.pipe(
  tap(v => console.log(`Emitted at ${testScheduler.now()}: ${v}`))
);

This will print the virtual time when the emission happened, allowing you to verify if your mental model of the operator’s timing matches the implementation.


Complete Example Session

// ============================================
// PART 1: SETUP
// ============================================
import { TestScheduler } from 'rxjs/testing';
const ts = new TestScheduler((a, e) => expect(a).toEqual(e));

// ============================================
// PART 2: SIMPLE EMISSION
// ============================================
ts.run(({ cold, expectObservable }) => {
  const s = cold('-a-b-|');
  expectObservable(s).toBe('-a-b-|');
});

// ============================================
// PART 3: GROUPED EMISSION
// ============================================
ts.run(({ cold, expectObservable }) => {
  const s = cold('-(ab)-|');
  expectObservable(s).toBe('-(ab)-|');
});

// ============================================
// PART 4: ERROR HANDLING
// ============================================
ts.run(({ cold, expectObservable }) => {
  const s = cold('-a-#');
  expectObservable(s).toBe('-a-#');
});

// ============================================
// PART 5: OPERATOR TESTING (MAP)
// ============================================
ts.run(({ cold, expectObservable }) => {
  const s = cold('-a-b-|');
  const e =      '-x-y-|';
  const op = s.pipe(map(v => v === 'a' ? 'x' : 'y'));
  expectObservable(op).toBe(e);
});

// ============================================
// PART 6: TIME-BASED OPERATOR (DEBOUNCE)
// ============================================
ts.run(({ cold, expectObservable }) => {
  // 'a' emitted at frame 1. debounce(30ms) = 3 frames.
  // Emission should occur at 1 + 3 = 4.
  const s = cold('-a--b---|');
  const e =      '----a---b---|';
  expectObservable(s.pipe(debounceTime(30))).toBe(e);
});

// ============================================
// PART 7: HOT OBSERVABLES
// ============================================
ts.run(({ hot, expectObservable }) => {
  // Hot observables start running immediately
  const h = hot('--a--b--|');
  expectObservable(h).toBe('--a--b--|');
});

// ============================================
// PART 8: SUBSCRIPTION VERIFICATION
// ============================================
ts.run(({ cold, expectObservable, expectSubscriptions }) => {
  const s = cold('-a---|');
  const subs =   '^----!'; // Sub at 1, unsub at 5
  expectObservable(s).toBe('-a---|');
  expectSubscriptions(s.subscriptions).toBe(subs);
});

// ============================================
// PART 9: COMPLEX SWITCHMAP
// ============================================
ts.run(({ cold, expectObservable }) => {
  const o = cold('-a---b-|');
  const i = cold('-1-2-|');
  // switchMap cancels inner on new outer
  const expected = '---1-2-----1-2-|';
  expectObservable(o.pipe(switchMap(() => i))).toBe(expected);
});

// ============================================
// PART 10: ADVANCED TIME ASSERTIONS
// ============================================
ts.run(({ cold, expectObservable }) => {
  const s = cold('a');
  // Use `time()` helper for clarity
  const delayTime = 30; // 3 frames
  expectObservable(s.pipe(delay(delayTime))).toBe('---a');
});

The session covered basic emissions, groupings, errors, operator testing, hot vs cold, subscription tracking, switchMap logic, and advanced time assertions.


Quick Reference

Marble Syntax (DSL)

CharacterMeaning
-1 frame (10ms default)
a-z, 0-9Emission values
``
#Error
()Grouping (same frame)
^Subscription start
!Subscription end

TestScheduler Helpers

HelperPurpose
cold(m)Creates a cold Observable
hot(m)Creates a hot Observable
expectObservable(o)Assert an observable’s timeline
expectSubscriptions(s)Assert subscription timeline
time(m)Convert marble string to ms

Common Operator Marbles

OperatorInputOutput
map(v => v+1)`-a-b-`
filter(v => v>1)`-1-2-`
take(1)`-a-b-`
delay(20)`-a-`

Best Practices

โœ… Do This:

// Use the run wrapper
ts.run(({ cold, expectObservable }) => { ... });             // โœ…

// Assert subscriptions to verify cancellation
expectSubscriptions(source.subscriptions).toBe('^---!');     // โœ…

// Group complex sync events
expectObservable(source).toBe('-(abc)-|');                   // โœ…

// Define expected timelines clearly
const expected = '---a';                                     // โœ…

โŒ Don’t Do This:

// Mix real timers with marble tests
setTimeout(() => { ... }, 100);                              // โŒ

// Use complex logic inside marble tests
expectObservable(op).toBe(complexMath(a));                   // โŒ

// Use 'any' in your assertions
expectObservable(op as any).toBe(e);                         // โŒ

// Ignore completion or error paths
expectObservable(op).toBe('---a'); // forgot the completion  // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Off-by-one timeMiscounting framesCount dashes carefully
Stalled testOperator missing completionAdd `
Flaky testsAccidentally using real timeAlways use testScheduler.run
Subscription errorNot asserting cancellationUse expectSubscriptions
Ambiguous valuesUsing generic ‘a’ for different inputsUse different letters

Real-World Examples

1. Simple mapping

const op = source.pipe(map(x => x + 1));
expectObservable(op).toBe('-b-c-|');

2. Filtering events

const op = source.pipe(filter(x => x > 1));
expectObservable(op).toBe('---b-|');

3. Error propagation

const op = source.pipe(map(() => { throw 'err' }));
expectObservable(op).toBe('-#', {}, 'err');

4. Debounce

expectObservable(s.pipe(debounceTime(20))).toBe('---a');

5. SwitchMap cancellation

expectObservable(s.pipe(switchMap(() => i))).toBe('---i');

6. Retry logic

expectObservable(s.pipe(retry(1))).toBe('-a-a-|');

7. CombineLatest

expectObservable(combineLatest([s1, s2])).toBe('-a-b');

8. Merge

expectObservable(merge(s1, s2)).toBe('-a-b-c');

9. TakeUntil

expectObservable(s.pipe(takeUntil(n))).toBe('-a|');

10. Scan/Accumulate

expectObservable(s.pipe(scan((a, b) => a + b))).toBe('-1-3');

Visual

Marble Timeline Anatomy

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  MARBLE STRING: -a-b-|                                 โ”‚
โ”‚                                                        โ”‚
โ”‚  Frame:   0 1 2 3 4 5                                  โ”‚
โ”‚  Event:     a   b   |                                  โ”‚
โ”‚                                                        โ”‚
โ”‚  'a' is at frame 1                                     โ”‚
โ”‚  'b' is at frame 3                                     โ”‚
โ”‚  '|' is at frame 5                                     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Cold vs Hot Observables

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  COLD: Subscriber starts the producer.                 โ”‚
โ”‚  0ms: Subscribed โ”€โ”€โ–บ Producer starts                   โ”‚
โ”‚                                                        โ”‚
โ”‚  HOT: Producer runs regardless of subscriber.          โ”‚
โ”‚  0ms: Producer starts                                  โ”‚
โ”‚  10ms: Subscriber attaches (might miss 0-10ms)         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Subscription Assertions

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  SUBSCRIPTION TIMELINE                                 โ”‚
โ”‚                                                        โ”‚
โ”‚  ^  = Subscription starts                              โ”‚
โ”‚  !  = Unsubscription                                   โ”‚
โ”‚                                                        โ”‚
โ”‚  ^-------!                                             โ”‚
โ”‚  (0-7 frames long)                                     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Test EngineTestScheduler
Virtual Time1 marble = 10ms (default)
DSL-, a-z, `
AssertionexpectObservable(o).toBe(m)
SubscriptionexpectSubscriptions(s.subscriptions).toBe(m)

Key takeaways:

  • Deterministic testing is mandatory for async code. TestScheduler provides a controlled environment where you dictate the flow of time.
  • Marble DSL is the language of streams. Learn the syntax (-, |, #, ()) to express complex timing scenarios with minimal code.
  • Virtual Time is synchronous. Marble tests execute in a single tick of the event loop, making them incredibly fast and reliable.
  • Always assert completion. Failing to include | or # in your marble strings leads to incomplete test coverage and hidden memory leaks.
  • Verify cancellation. Use expectSubscriptions to ensure your operators (like switchMap) are cleaning up after themselves.

Remember: Marble testing is not just about checking values; it is about checking timing. When you write a marble test, you are proving that your operator produces the right result at the exact right moment. This rigor is what separates robust reactive systems from brittle ones. Use the DSL to document your streams, trust the TestScheduler to handle the clock, and you will find that even the most complex asynchronous bugs become trivial to isolate.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!