百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
O

observer-spy

> 前端框架
开源

这个库使 RxJS 可观测对象的测试变得简单!

375 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

这个库使 RxJS 可观测对象的测试变得简单!

@hirez_io/observer-spy

This library makes RxJS Observables testing easy!

Table of Contents

  • Installation

  • The Problem

  • The Solution

  • Usage

    • subscribeSpyTo(observable)

    • onComplete (using async + await)

    • Spying on Errors (expectErrors)

    • onError (using async + await)

    • Manually Creating Spies

    • Auto Unsubscribing

    • Testing Sync Logic

    • Testing Async Logic

      • ▶ RxJS + Angular: use fakeAsync

      • ▶ RxJS + Promises: use async + await

      • ▶ RxJS Timers / Animations: use fakeTime

      • ▶ RxJS + AJAX calls:

  • Wanna become a PRO Observables tester?

  • How to Contribute

  • Code Of Conduct

  • Contributors ✨

  • License

Installation

bash
yarn add -D @hirez_io/observer-spy

or

bash
npm install -D @hirez_io/observer-spy

THE PROBLEM: Testing RxJS observables is hard!

Especially when testing advanced use cases.

Until this library, the common way to test observables was to use Marble tests

What are the disadvantages of Marble Tests?

Marble tests are very powerful, but unfortunately for most tests they are conceptually very complicated to learn and to reason about..

You need to learn and understand cold and hot observables, schedulers and to learn a new syntax just to test a simple observable chain.

More complex observable chains tests get even harder to read and to maintain.

THE SOLUTION: Observer Spies!

The Observer-Spy library was created to present a viable alternative to Marble Tests.

An alternative which we believe is:

  • ✅ Easier to understand

  • ✅ Reduces the complexity

  • ✅ Makes observables tests cleaner

Here's what people had to say:



Why Observer-Spy is easier?

Marble test:

…

Observer Spy Test:

javascript

import { subscribeSpyTo } from '@hirez_io/observer-spy';

it('should filter even numbers and multiply each number by 10', () => {
  
    const result$ = of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10).pipe(
      filter(n => n % 2 !== 0),
      map(x => x * 10)
    );

    const observerSpy = subscribeSpyTo(result$);

    expect(observerSpy.getValues()).toEqual([10, 30, 50, 70, 90]);

  })
});

You generally want to test the outcome of your action instead of implementation details [like how many frames were between each value].

For most production app use cases, if enough (virtual) time passes testing the received values or their order should be sufficient.

This library gives you the tool to investigate your spy about the values it received and their order.

(The idea was inspired by Reactive Programming with RxJava)

Usage

const observerSpy = subscribeSpyTo(observable)

In order to test Observables you can use the subscribeSpyTo function:

…

Wait for onComplete before expecting the result (using async + await)

javascript
it('should support async await for onComplete()', async () => {
  
  const fakeObservable = of('first', 'second', 'third');

  const observerSpy = subscribeSpyTo(fakeObservable);

// 
  await observerSpy.onComplete(); //  {
  //     expect(observerSpy.receivedComplete()).toBe(true);
  //   }));
});

Spy on errors with receivedError and getError

⚠ You MUST configure expectErrors to catch errors!

This is to avoid swallowing unexpected errors (more details here)

javascript

it('should spy on Observable errors', () => {

  const fakeObservable = throwError('FAKE ERROR');

  const observerSpy = subscribeSpyTo(fakeObservable, {expectErrors: true});

  expect(observerSpy.receivedError()).toBe(true);

  expect(observerSpy.getError()).toEqual('FAKE ERROR');
});

Wait for onError before expecting the result (using async + await)

…

If you need to spy on errors, make sure to set the expectErrors property:

javascript
it('should spy on Observable errors', () => {
  
  const fakeObservable = throwError('OOPS');

  const observerSpy = new ObserverSpy({expectErrors: true}); // /node_modules/@hirez_io/observer-spy/dist/setup-auto-unsubscribe.js'],
}

⚒ Configuring Angular (Karma + Jasmine) with autoUnsubscribe

This will add a root level afterEach() once that auto unsubscribes observer spies.

Add this to your test.ts -

typescript
// test.ts
// ~~~~~~~

import { autoUnsubscribe } from '@hirez_io/observer-spy';

autoUnsubscribe();

⚒ Manually adding a subscription with queueForAutoUnsubscribe

If you configured your environment to "autoUnsubscribe" and want your manually created spies (via new ObserverSpy()) to be "auto unsubscribed" as well, you can use queueForAutoUnsubscribe(subscription).

It accepts any Unsubscribable object which has an unsubscribe() method -

javascript
import { queueForAutoUnsubscribe } from '@hirez_io/observer-spy';

it('should spy on Observable values', () => {
  const fakeValues = ['first', 'second', 'third'];
  const fakeObservable = of(...fakeValues);

  const observerSpy = new ObserverSpy();
  const subscription = fakeObservable.subscribe(observerSpy)
  
  // This will auto unsubscribe this subscription after the test ends
  // (if you configured "autoUnsubscribe()" in your environment)
  queueForAutoUnsubscribe(subscription);

  // ... rest of the test

});

This will ensure your manually created spies are auto unsubscribed at the end of each test.

Testing Sync Logic

▶ Synchronous RxJS

RxJS - without delaying operators or async execution contexts - will run synchronously. This is the simplest use case; where our it() does not need any special asynchronous plugins.

typescript
it('should run synchronously', () => {
  const observerSpy = subscribeSpyTo(from(['first', 'second', 'third']));
  expect(spy.getValuesLength()).toBe(3);
});

Testing Async Logic

If you're not using Angular and have RxJS async operators like delay or timeout

Use fakeTime with flush() to simulate the passage of time (detailed explanation) -

▶ RxJS + Angular: use fakeAsync

With Angular, you can control time in a much more versatile way.

Just use fakeAsync (and tick if you need it):

javascript
// ... other imports
import { subscribeSpyTo } from '@hirez_io/observer-spy';
import { fakeAsync, tick } from '@angular/core/testing';

it('should test Angular code with delay', fakeAsync(() => {
  
  const fakeObservable = of('fake value').pipe(delay(1000));

  const observerSpy = subscribeSpyTo(fakeObservable);

  tick(1000);

  expect(observerSpy.getLastValue()).toEqual('fake value');
}));

▶ RxJS + Promises: use async + await

Since Promise(s) are MicroTasks, we should consider them to resolve asynchronously.

For code using Promise(s) without timeouts or intervals, just use async + await with the onComplete() method:

javascript
// ... other imports
import { subscribeSpyTo } from '@hirez_io/observer-spy';

it('should work with promises', async () => {

  const fakeService = {
    getData() {
      return Promise.resolve('fake data');
    },
  };
  const fakeObservable = defer(() => fakeService.getData());

  const observerSpy = subscribeSpyTo(fakeObservable);

  await observerSpy.onComplete();

  expect(observerSpy.getLastValue()).toEqual('fake data');
});

▶ RxJS Timers / Animations: use fakeTime

RxJS code that has time-based logic (e.g using timeouts / intervals / animations) will emit asynchronously.

fakeTime() is a custom utility function that wraps the test callback which is perfect for most of these use-cases.

It does the following things:

  1. Changes the RxJS AsyncScheduler delegate to use VirtualTimeScheduler and use "virtual time".
  2. Passes a flush() function you can call whenever you want to virtually pass time forward.
  3. Works well with done if you pass it as the second parameter (instead of the first)

Example:

…

▶ RxJS + AJAX calls:

Asynchronous REST calls (using axios, http, fetch, etc.) should not be tested in a unit / micro test... Test those in an integration test!

Wanna become a PRO Observables tester?

In Angular Class Testing In action course Shai Reznik goes over all the differences and show you how to use observer spies to test complex Observable chains with switchMap, interval etc...

Contributing

Want to contribute? Yayy!

Please read and follow our Contributing Guidelines to learn what are the right steps to take before contributing your time, effort and code.

Thanks

Code Of Conduct

Be kind to each other and please read our code of conduct.

Contributors ✨

Thanks goes to these wonderful people (emoji key):

Shai Reznik ⚠️

Edouard Bozon ⚠️

Adam Smith

Katharina Koal ⚠️

Thomas Burleson ⚠️

Levent Arman Özak

Petr Zahradník ⚠️

Jason Landbridge

This project follows the all-contributors specification. Contributions of any kind welcome!

License

MIT

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

TypeScriptangularjasminejestmarble-tests

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类前端框架
定价开源

> 相关工具

R
React
用于构建用户界面的 JavaScript 库
V
Vue.js
渐进式 JavaScript 框架
N
Next.js
基于 React 的全栈 Web 框架