Search code examples
javascripttestingjasminethrow

Jasmine .and.throwError() is not caught by .catch in original code


I'm writing a test for a function, and have to trigger the .catch part of that function, but Jasmine's spiesfor some reason can't do that. Method to be tested:

foo(){
doStuff()
.catch((error) => {
    //stuff I still have to test
    bar()
})

}

doStuff() returns a Promise (hence the .catch-Setup), but for this test it's supposed to throw an error.

Here is my test:

it('tests the error handling of foo',(done) =>{
spyOn(object,'foo').and.throwError('Test Error');

object.foo();

expect(object.bar).toHaveBeenCalled();
done();

});

Is the way I'm approaching this wrong? Is that an error with Jasmine? (Google didn't find anything) [I stick to the (done) setup because almost all other tests are async and I want to keep the style]

[I cannot change the code to be tested]


Solution

  • If you call and.throwError(...); you throw the error within the test method.

    You can try to return a Promise rejection instead:

    spyOn(object, 'foo').and.rejectWith(new Error('Test Error'));