How to test an RxJS operation that throws an error

Note Statistics

Note Statistics

  • Viewed 183 times
Sun, 12/27/2020 - 14:12

Let's say we defined and operation that thows an error for certain use cases

Let's define a operator that throws an error.


function myOpertator() {
  return throwError(new Error('Something bad happened'));
}

Include required RxJS functions

import { throwError } from 'rxjs'
import { catchError } from 'rxjs/operators'

Testing with Jest

 test('must throw an error', done => {
     myOpertator().pipe(catchError((e) => [e])).subscribe(e => {
        expect(e).toBeInstanceOf(Error)
        done()
      })
    })

Testing with Chai

 it('must throw an error',  done => {
     myOpertator().pipe(catchError((e) => [e])).subscribe(e => {
        expect(e).to.be.an.instanceof(Error)
        done()
      })
    })
Authored by
Tags