How to return HTTP error response in TypeMoq

383 Views Asked by At

I'm trying to write a TypeScript unit test using TypeMoq that mocks an HTTP request and returns an error response. When returning a basic object as expected there is no problem, but when trying to return an HTTP error response then the test always fails due to an exception being thrown.

How can I write a mock setup using TypeMoq that returns an HTTP error response and doesn't throw an exception? If there is an HTTP response error code, then I want to set the "component.SomeProperty" property.

mock.setup(x => x.getHttpData()).throws(() => new Error('error'));

expect(component.SomeProperty).toBe('someValue');
1

There are 1 best solutions below

0
denkan On BEST ANSWER

Just tackled the same issue. Got it working by returning a throwError():

import { throwError } from 'rxjs';

...

mock.setup(x => x.getHttpData()).returns(() => throwError(new Error('error')));