František Žiačik
František Žiačik

Reputation: 7614

Correct way to unit-test observable stream being fed

I use this to test that the service adds an item to observable stream of errors.

it('can be subscribed for errors', () => {
    let testError = new Error('Some error.');
    let called = false;
    let subscription = service.onError.subscribe(error => {
        called = true;
        expect(error).toEqual(testError);
    });
    /// This makes an error to be added to onError stream
    service.setError(testError);
    expect(called).toEqual(true);
});

I use the called variable to make sure that the subscription callback was actually called. Otherwise the test would pass when it shouldn't. But it doesn't seem right to me. Also, it wouldn't work if the stream was asynchronous.

Is this a good way to test that? If not, how to do it properly?

EDIT: this is the class that's being tested. It's in typescript, actually.

import { ReplaySubject } from 'rxjs/Rx';

export class ErrorService {
    private error: Error;

    public onError: ReplaySubject<Error> = new ReplaySubject<Error>();

    constructor() {
    }

    public setError = (error: Error) => {
        this.error = error;
        console.error(error);
        this.onError.next(error);
    }

    public getError() {
        return this.error;
    }

    public hasError() {
        return !!this.error;
    }
}

Upvotes: 1

Views: 240

Answers (1)

KwintenP
KwintenP

Reputation: 4775

The way you are testing is good. You are:

  • Checking if the value is correct with expect statement.
  • Checking the fact the expect statement is being executed.

Especially the last part is important otherwise the expect might not be triggered and the test will falsely pass.

Upvotes: 1

Related Questions