Coder Social home page Coder Social logo

katharinakoal / observer-spy Goto Github PK

View Code? Open in Web Editor NEW

This project forked from hirezio/observer-spy

0.0 0.0 0.0 460 KB

A simple little class and a helper function that help make Observable testing a breeze

License: MIT License

JavaScript 2.63% TypeScript 97.37%

observer-spy's Introduction

@hirez_io/observer-spy ๐Ÿ‘€๐Ÿ’ช

A simple little class and a helper function that help make Observable testing a breeze

npm version npm downloads Build Status License: MIT codecov All Contributors

What's the problem?

Testing RxJS observables is usually hard, especially when testing advanced use cases.

This library:

โœ… Is easy to understand

โœ… Reduces the complexity

โœ… Makes testing advanced observables easy

Installation

yarn add -D @hirez_io/observer-spy

or

npm install -D @hirez_io/observer-spy

Observer Spies VS Marble Tests

Marble tests are very powerful, but at the same time can be very complicated to learn and to reason about for some people.

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.

That's why this library was created - to present an alternative to marble tests, which we believe is cleaner and easier to understand and to use.

How observer spies are cleaner?

You generally want to test the outcome of your action, not implementation details like exactly how many frames were between each value.

The order of recieved values represents the desired outcome for most production app use cases.

Most of the time, if enough (virtual) time passes until the expectation in my test, it should be sufficient to prove whether the expected outcome is valid or not.

Usage

new ObserverSpy()

In order to test observables, you can use an ObserverSpy instance to "record" all the messages a source observable emits and to get them as an array.

You can also spy on the error or complete states of the observer.

You can use done or async / await to wait for onComplete to be called as well.

Example:

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

it('should spy on Observable values', () => {
  const observerSpy = new ObserverSpy();
  // BTW, if you're using TypeScript you can declare it with a generic:
  // const observerSpy: ObserverSpy<string> = new ObserverSpy();

  const fakeValues = ['first', 'second', 'third'];
  const fakeObservable = of(...fakeValues);

  const subscription = fakeObservable.subscribe(observerSpy);

  // DO SOME LOGIC HERE

  // unsubscribing is optional, it's good for stopping intervals etc
  subscription.unsubscribe();

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

  expect(observerSpy.getValues()).toEqual(fakeValues);

  expect(observerSpy.getValuesLength()).toEqual(3);

  expect(observerSpy.getFirstValue()).toEqual('first');

  expect(observerSpy.getValueAt(1)).toEqual('second');

  expect(observerSpy.getLastValue()).toEqual('third');

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

  observerSpy.onComplete(() => {
    expect(observerSpy.receivedComplete()).toBe(true);
  }));
});

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

  fakeObservable.subscribe(observerSpy);

  await observerSpy.onComplete();

  expect(observerSpy.receivedComplete()).toBe(true);
});

it('should spy on Observable errors', () => {
  const observerSpy = new ObserverSpy();

  const fakeObservable = throwError('FAKE ERROR');

  fakeObservable.subscribe(observerSpy);

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

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

Quick Usage with subscribeAndSpyOn(observable)

You can also create an ObserverSpy and immediately subscribe to an observable with this simple helper function. Observer spies generated that way will provide an additional unsubscribe() method that you might want to call if your source observable does not complete or does not get terminated by an error while testing.

Example:

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

it('should immediately subscribe and spy on Observable ', () => {
  const fakeObservable = of('first', 'second', 'third');

  // get an "ObserverSpyWithSubscription"
  const observerSpy = subscribeAndSpyOn(fakeObservable);
  // and optionally unsubscribe
  observerSpy.unsubscribe();

  expect(observerSpy.getFirstValue()).toEqual('first');

  // or use the shorthand version:
  expect(subscribeAndSpyOn(fakeObservable).getFirstValue()).toEqual('first');
});

Testing Async Observables

it('should do something', fakeTime((flush) => { ... flush(); });

You can use the fakeTime utility function and call flush() to simulate the passage of time if you have any async operators like delay or timeout in your tests.


Now, let's see some use cases and their solutions:

โ–ถ For Angular code - just use fakeAsync

You can control time in a much more versatile way and clear the microtasks queue (for promises) without using the done() which is much more convenient.

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

Example:

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

it('should test Angular code with delay', fakeAsync(() => {
  const observerSpy = new ObserverSpy();

  const fakeObservable = of('fake value').pipe(delay(1000));

  const sub = fakeObservable.subscribe(observerSpy);

  tick(1000);

  sub.unsubscribe();

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

โ–ถ For microtasks related code (promises, but no timeouts / intervals) - just use async await or done()

You can use the onComplete method to wait for a completion before checking the outcome. Chose between async + await or done, both work.

Example:

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

it('should work with observables', async () => {
  const observerSpy: ObserverSpy<string> = new ObserverSpy();

  const fakeService = {
    getData() {
      return defer(() => of('fake data'));
    },
  };
  const fakeObservable = of('').pipe(switchMap(() => fakeService.getData()));

  fakeObservable.subscribe(observerSpy);

  await observerSpy.onComplete();

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

it('should work with promises', async () => {
  const observerSpy: ObserverSpy<string> = new ObserverSpy();

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

  fakeObservable.subscribe(observerSpy);

  await observerSpy.onComplete();

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

it('should work with promises and "done()"', (done) => {
  const observerSpy: ObserverSpy<string> = new ObserverSpy();

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

  fakeObservable.subscribe(observerSpy);

  observerSpy.onComplete(() => {
    expect(observerSpy.getLastValue()).toEqual('fake data');
    done();
  });
});

โ–ถ For time based rxjs code (timeouts / intervals / animations) - use fakeTime

fakeTime is a utility function that wraps the test callback.

It does the following things:

  1. Changes the AsyncScheduler delegate to use VirtualTimeScheduler (which gives you the ability to use "virtual time" instead of having long tests)
  2. Passes a flush function you can call to flush() the virtual time (pass time forward)
  3. Works well with done if you pass it as the second parameter (instead of the first)

Example:

// ... other imports
import { ObserverSpy, fakeTime } from '@hirez_io/observer-spy';

it(
  'should handle delays with a virtual scheduler',
  fakeTime((flush) => {
    const VALUES = ['first', 'second', 'third'];
    const observerSpy: ObserverSpy<string> = new ObserverSpy();
    const delayedObservable: Observable<string> = of(...VALUES).pipe(delay(20000));

    const sub = delayedObservable.subscribe(observerSpy);
    flush();
    sub.unsubscribe();

    expect(observerSpy.getValues()).toEqual(VALUES);
  })
);

it(
  'should handle be able to deal with done functionality as well',
  fakeTime((flush, done) => {
    const VALUES = ['first', 'second', 'third'];
    const observerSpy: ObserverSpy<string> = new ObserverSpy();
    const delayedObservable: Observable<string> = of(...VALUES).pipe(delay(20000));

    const sub = delayedObservable.subscribe(observerSpy);
    flush();
    sub.unsubscribe();

    observerSpy.onComplete(() => {
      expect(observerSpy.getValues()).toEqual(VALUES);
      done();
    });
  })
);

โ–ถ For ajax calls (http) - they shouldn't be tested in a unit / micro test anyway... ๐Ÿ˜œ

Yeah. Test those in an integration test!

Wanna learn more?

In my class testing In action course I go over all the differences and show you how to use this library to test stuff like switchMap, interval etc...

Contributors โœจ

Thanks goes to these wonderful people (emoji key):


Shai Reznik

๐Ÿ’ป โš ๏ธ ๐Ÿš‡ ๐Ÿ“– ๐Ÿšง ๐Ÿ‘€ ๐Ÿค”

Edouard Bozon

๐Ÿ’ป โš ๏ธ ๐Ÿ“– ๐Ÿค”

Adam Smith

๐Ÿ“–

Katharina Koal

๐Ÿ’ป โš ๏ธ ๐Ÿ“– ๐Ÿค” ๐Ÿ›

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

observer-spy's People

Contributors

allcontributors[bot] avatar burkybang avatar edbzn avatar katharinakoal avatar shairez avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.