• Stars
    star
    300
  • Rank 138,870 (Top 3 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

An RxJS marble testing library for any test framework

rxjs-marbles

GitHub License NPM version Downloads Build status dependency status devDependency Status peerDependency Status Greenkeeper badge

What is it?

rxjs-marbles is an RxJS marble testing library that should be compatible with any test framework. It wraps the RxJS TestScheduler and provides methods similar to the helper methods used the TestScheduler API.

It can be used with AVA, Jasmine, Jest, Mocha or Tape in the browser or in Node and it supports CommonJS and ES module bundlers.

Why might you need it?

I created this package because I wanted to use RxJS marble tests in a number of projects and those projects used different test frameworks.

There are a number of marble testing packages available - including the Mocha-based implementation in RxJS itself - but I wanted something that was simple, didn't involve messing with globals and beforeEach/afterEach functions and was consistent across test frameworks.

If you are looking for something similar, this might suit.

Install

Install the package using NPM:

npm install rxjs-marbles --save-dev

Getting started

If you're just getting started with marble testing, you might be interested in how I wasted some of my time by not carefully reading the manual: RxJS Marble Testing: RTFM.

In particular, you should read the RxJS documentation on marble syntax and synchronous assertion.

Usage

rxjs-marbles contains framework-specific import locations. If there is a location for the test framework that you are using, you should use the specific import. Doing so will ensure that you receive the best possible integration with your test framework.

For example, importing from "rxjs-marbles/jest" will ensure that Jest's matcher is used and the output for test failures will be much prettier.

With Mocha

Instead of passing your test function directly to it, pass it to the library's marbles function, like this:

import { marbles } from "rxjs-marbles/mocha";
import { map } from "rxjs/operators";

describe("rxjs-marbles", () => {

    it("should support marble tests", marbles(m => {

        const source =  m.hot("--^-a-b-c-|");
        const subs =            "^-------!";
        const expected =        "--b-c-d-|";

        const destination = source.pipe(
            map(value => String.fromCharCode(value.charCodeAt(0) + 1))
        );
        m.expect(destination).toBeObservable(expected);
        m.expect(source).toHaveSubscriptions(subs);
    }));
});

With other test frameworks

To see how rxjs-marbles can be used with other test frameworks, see the examples within the repository.

With AVA and Tape, the callback passed to the marbles function will receive an addional argument - the AVA ExecutionContext or the Tape Test - which can be used to specify the number of assertions in the test plan. See the framework-specific examples for details.

Using cases for test variations

In addition to the marbles function, the library exports a cases function that can be used to reduce test boilerplate by specifying multiple cases for variations of a single test. The API is based on that of jest-in-case, but also includes the marbles context.

The cases implementation is framework-specific, so the import must specify the framework. For example, with Mocha, you would import cases and use it instead of the it function, like this:

import { cases } from "rxjs-marbles/mocha";
import { map } from "rxjs/operators";

describe("rxjs-marbles", () => {

    cases("should support cases", (m, c) => {

        const source =  m.hot(c.s);
        const destination = source.pipe(
            map(value => String.fromCharCode(value.charCodeAt(0) + 1))
        );
        m.expect(destination).toBeObservable(c.e);

    }, {
        "non-empty": {
            s: "-a-b-c-|",
            e: "-b-c-d-|"
        },
        "empty": {
            s: "-|",
            e: "-|"
        }
    });
});

TestScheduler behaviour changes in RxJS version 6

In RxJS version 6, a run method was added to the TestScheduler and when it's used, the scheduler's behaviour is significantly changed.

rxjs-marbles now defaults to using the scheduler's run method. To use the scheduler's old behaviour, you can call the configure function, passing { run: false }, like this:

import { configure } from "rxjs-marbles/mocha";
const { cases, marbles } = configure({ run: false });

Dealing with deeply-nested schedulers

WARNING: bind is deprecated and can only be used with configure({ run: false }).

Sometimes, passing the TestScheduler instance to the code under test can be tedious. The context includes a bind method that can be used to bind a scheduler's now and schedule methods to those of the context's TestScheduler.

bind can be passed specific scheduler instances or can be called with no arguments to bind RxJS's animationFrame, asap, async and queue schedulers to the context's TestScheduler.

For example:

it("should support binding non-test schedulers", marbles(m => {

    m.bind();

    const source =  m.hot("--^-a-b-c-|");
    const subs =            "^--------!";
    const expected =        "---a-b-c-|";

    // Note that delay is not passed a scheduler:
    const destination = source.delay(m.time("-|"));
    m.expect(destination).toBeObservable(expected);
    m.expect(source).toHaveSubscriptions(subs);
}));

Changing the time per frame

WARNING: reframe is deprecated and can only be used with configure({ run: false }).

The RxJS TestScheduler defaults to 10 virtual milliseconds per frame (each character in the diagram represents a frame) with a maximum of 750 virtual milliseconds for each test.

If the default is not suitable for your test, you can change it by calling the context's reframe method, specifying the time per frame and the (optional) maximum time. The reframe method must be called before any of the cold, flush, hot or time methods are called.

The examples include tests that use reframe.

Alternate assertion methods

If the BDD syntax is something you really don't like, there are some alternative methods on the Context that are more terse:

const source =  m.hot("--^-a-b-c-|", values);
const subs =            "^-------!";
const expected = m.cold("--b-c-d-|", values);

const destination = source.map((value) => value + 1);
m.equal(destination, expected);
m.has(source, subs);

API

The rxjs-marbles API includes the following functions:

configure

interface Configuration {
    assert?: (value: any, message: string) => void;
    assertDeepEqual?: (a: any, b: any) => void;
    frameworkMatcher?: boolean;
    run?: boolean;
}

function configure(options: Configuration): { marbles: MarblesFunction };

The configure method can be used to specify the assertion functions that are to be used. Calling it is optional; it's only necessary if particular assertion functions are to be used. It returns an object containing a marbles function that will use the specified configuration.

The default implementations simply perform the assertion and throw an error for failed assertions.

marbles

function marbles(test: (context: Context) => any): () => any;
function marbles<T>(test: (context: Context, t: T) => any): (t: T) => any;

marbles is passed the test function, which it wraps, passing the wrapper to the test framework. When the test function is called, it is passed the Context - which contains methods that correspond to the TestScheduler helper methods:

interface Context {
    autoFlush: boolean;
    bind(...schedulers: IScheduler[]): void;
    cold<T = any>(marbles: string, values?: any, error?: any): ColdObservable<T>;
    configure(options: Configuration): void;
    equal<T = any>(actual: Observable<T>, expected: Observable<T>): void;
    equal<T = any>(actual: Observable<T>, expected: string, values?: { [key: string]: T }, error?: any): void;
    equal<T = any>(actual: Observable<T>, subscription: string, expected: Observable<T>): void;
    equal<T = any>(actual: Observable<T>, subscription: string, expected: string, values?: { [key: string]: T }, error?: any): void;
    expect<T = any>(actual: Observable<T>, subscription?: string): Expect<T>;
    flush(): void;
    has<T = any>(actual: Observable<T>, expected: string | string[]): void;
    hot<T = any>(marbles: string, values?: any, error?: any): HotObservable<T>;
    reframe(timePerFrame: number, maxTime?: number): void;
    readonly scheduler: TestScheduler;
    teardown(): void;
    time(marbles: string): number;
}

interface Expect<T> {
    toBeObservable(expected: ColdObservable<T> | HotObservable<T>): void;
    toBeObservable(expected: string, values?: { [key: string]: T }, error?: any): void;
    toHaveSubscriptions(expected: string | string[]): void;
}

observe

In Jasmine, Jest and Mocha, the test framework recognises asynchronous tests by their taking a done callback or returning a promise.

The observe helper can be useful when an observable cannot be tested using a marble test. Instead, expectations can be added to the observable stream and the observable can be returned from the test.

See the examples for usage.

fakeSchedulers

With Jest and Jasmine, the test framework can be configured to use its own concept of fake time. AVA, Mocha and Tape don't have built-in support for fake time, but the functionality can be added via sinon.useFakeTimers().

In some situations, testing asynchronous observables with marble tests can be awkward. Where testing with marble tests is too difficult, it's possible to test observables using the test framework's concept of fake time, but the now method of the AsyncScheduler has to be patched. The fakeSchedulers helper can be used to do this.

See the examples for usage.

Also, I've written an article on the fakeSchedulers function: RxJS: Testing with Fake Time.

More Repositories

1

rxjs-spy

A debugging library for RxJS
TypeScript
700
star
2

rxjs-tslint-rules

TSLint rules for RxJS
TypeScript
371
star
3

eslint-plugin-rxjs

ESLint rules for RxJS
TypeScript
286
star
4

rxjs-etc

Observables and operators for RxJS
TypeScript
216
star
5

ts-action

TypeScript action creators for Redux
TypeScript
183
star
6

eslint-plugin-etc

More general-purpose (TypeScript-related) ESLint rules
TypeScript
142
star
7

rxjs-observe

A library for observing an object's property assignments and method calls
TypeScript
96
star
8

eslint-plugin-rxjs-angular

ESLint rules for RxJS and Angular
TypeScript
96
star
9

tslint-etc

More rules for TSLint
TypeScript
43
star
10

firebase-key

Firebase key utility and encoding/decoding functions
TypeScript
40
star
11

rxjs-spy-devtools

Chrome DevTools for rxjs-spy
TypeScript
39
star
12

firebase-nightlight

An in-memory, JavaScript mock for the Firebase Web API
TypeScript
37
star
13

ts-action-operators

TypeScript action operators for NgRx and redux-observable
TypeScript
33
star
14

ts-snippet

A TypeScript snippet compiler for any test framework
TypeScript
32
star
15

eslint-plugin-react-etc

More ESLint rules for React
TypeScript
16
star
16

devtools-example

DevTools extension examples
JavaScript
16
star
17

eslint-etc

Utils for ESLint TypeScript rules
TypeScript
15
star
18

rxjs-xyz

RxJS community packages
JavaScript
14
star
19

rxjs-pluggables

RxJS observables and operators with pluggable strategies
TypeScript
14
star
20

firebase-thermite

Firebase RxJS observables
TypeScript
13
star
21

rxjs-traits

RxJS Traits for Static Analysis
TypeScript
13
star
22

rxjs-report-usage

Report a project's RxJS API usage to the core team
JavaScript
10
star
23

rxjs-interop

Observable interop helpers for RxJS
TypeScript
8
star
24

eslint-plugin-rxjs-traits

TypeScript
8
star
25

blog

Blog post Markdown content
Shell
6
star
26

tsutils-etc

TypeScript
6
star
27

recompose-etc

React function components and higher-order components based on recompose and RxJS
TypeScript
4
star
28

cartant

3
star
29

memoize-resolver

A general-purpose key resolver for memoize
TypeScript
3
star
30

eslint-plugin-dtslint

ESLint rules for dtslint tests
TypeScript
2
star
31

eslint-issues

A repo for reproducing ESLint plugin problems
TypeScript
1
star
32

eslint-config-rxjs

JavaScript
1
star
33

eslint-config-etc

JavaScript
1
star
34

eslint-config

JavaScript
1
star
35

eslint-config-react

JavaScript
1
star