Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rxjs how to expect an observable to throw error

In my TypeScript app I have a method that return an rxjs Observable which, in a certain case, can return throwError:

import { throwError } from 'rxjs';

// ...

getSomeData(inputValue): Observable<string> {
  if (!inputValue) {
    return throwError('Missing inputValue!');
  }

  // ...
}

how can I write a test to cover this specific case?

like image 599
Francesco Borzi Avatar asked Sep 05 '19 11:09

Francesco Borzi


3 Answers

You can test it using RxJS Marble diagram tests. Here's how:

const getSomeData = (inputValue: string): Observable<string> => {
  if (!inputValue) {
    return throwError('Missing inputValue!');
  }

  // e.g.
  return of(inputValue);
};

describe('Error test', () => {

  let scheduler: TestScheduler;

  beforeEach(() => {
    scheduler = new TestScheduler((actual, expected) => {
      expect(actual).toEqual(expected);
    });
  });

  it('should throw an error if an invalid value has been sent', () => {
    scheduler.run(({ expectObservable }) => {

      const expectedMarbles = '#'; // # indicates an error terminal event

      const result$ = getSomeData(''); // an empty string is falsy

      expectObservable(result$).toBe(expectedMarbles, null, 'Missing inputValue!');
    });
  });

  it('should emit an inputValue and immediately complete', () => {
    scheduler.run(({ expectObservable }) => {

      const expectedMarbles = '(a|)';

      const result$ = getSomeData('Some valid string');

      expectObservable(result$).toBe(expectedMarbles, { a: 'Some valid string' });
    });
  });
});

For more info on how to write these tests, please take a look at this link.

like image 143
Mladen Avatar answered Sep 29 '22 18:09

Mladen


I imagine your full case resembles something like this

// first there is something that emits an Observable
export function doSomethingThatReturnsAnObservable() {
  return createSomehowFirstObservable()
  .pipe(
     // then you take the data emitted by the first Observable 
     // and try to do something else which will emit another Observable
     // therefore you have to use an operator like concatMap or switchMap
     // this something else is where your error condition can occur
     // and it is where we use your getSomeData() function
     switchMap(inputValue => getSomeData(inputValue))
  );
}
}

// eventually, somewhere else, you subscribe
doSomethingThatReturnsAnObservable()
.subscribe(
   data => doStuff(data),
   error => handleError(error),
   () => doSomethingWhenCompleted()
)

A test for the error condition could look something like this

it('test error condition'), done => {
   // create the context so that the call to the code generates an error condition
   .....
   doSomethingThatReturnsAnObservable()
   .subscribe(
      null, // you are not interested in the case something is emitted
      error => {
        expect(error).to.equal(....);
        done();
      },
      () => {
        // this code should not be executed since an error condition is expected
        done('Error, the Observable is expected to error and not complete');
      }
   )
})
like image 33
Picci Avatar answered Sep 29 '22 18:09

Picci


In addition to lagoman's answer. You could simplify the way to get the testScheduler.

describe('Error test', () => {  
  it('should throw an error if an invalid value has been sent', () => {
    getTestScheduler().run(({ expectObservable }) => { // getTestScheduler from jasmine-marbles package

      const expectedMarbles = '#'; // # indicates an error terminal event

      const result$ = getSomeData(''); // an empty string is falsy

      expectObservable(result$).toBe(expectedMarbles, null, 'Missing inputValue!');
    });
  });

  it('should emit an inputValue and immediately complete', () => {
    getTestScheduler().run(({ expectObservable }) => {

      const expectedMarbles = '(a|)';

      const result$ = getSomeData('Some valid string');

      expectObservable(result$).toBe(expectedMarbles, { a: 'Some valid string' });
    });
  });
});
like image 33
davidvdijk Avatar answered Sep 29 '22 17:09

davidvdijk