I'm unit testing a component on Angular. Here I'm calling a function from an external service and artificially throwing an error in order to test how the component handles the error.
To do so, I need my error to be something like that
{ statusCode: 401, code: 'LOGIN_FAILED' }
However, the Jasmine throwError method only throws a single string passed as an argument. Is there a workaround or a method I don't know so I can throw an object?
Here is my code so far:
fit('should display error message if login failure', () => {
// should throw ({ statusCode: 401, code: 'LOGIN_FAILED' });
const spyLogin = spyOn(appUserApi, 'loginUser').and.throwError('test');
fillForm('toto@gmail.com', '1234');
submitForm();
// expect stuff here
});
I found a solution: use returnValue() instead of throwError() from the stub Then in the returned value your can throw whatever your want using rxjs throwError()
spyOn(appUserApi, 'loginDoctor')
.and
.returnValue(
throwError({ statusCode: 401, code: 'LOGIN_FAILED' })
);
Important note: here, throwError() comes from rxjs, not from jasmine spy!