jest-fetch-mock icon indicating copy to clipboard operation
jest-fetch-mock copied to clipboard

How to check raising error by !response.ok ?

Open viT-1 opened this issue 6 years ago • 6 comments

jest-fetch-mock v3.0.1

Can't catch error =(

PointSvc.fetchData has code:

const resp = await fetch(`/someUrl/?search=${params.label}`);
if (!resp.ok)
	throw new Error(resp.statusText);

PointSvc.spec.ts:

expect.assertions(1);
const statusText = 'Shit happens!';
fetchMock.mockResponseOnce('fail', {
	headers: { 'content-type': 'text/plain; charset=UTF-8' },
	status: 401,
	statusText,
});

expect(() => {
	PointSvc.fetchData({ label: 'anysearch' });
})
	.toThrow(statusText);

Result: Received function did not throw

viT-1 avatar Jan 29 '20 07:01 viT-1

I had something like,

it('should throw an error where response is not ok', async () => { fetchMock.mockReject(new Error('Internal Server Error')); const userSettings = new ClientSettingsBuilder();

		const response = ApiService.send({
			baseUrl: Configuration.url,
			payload: userSettings,
			model,
			endpoint: 'xyz.json'
		});

		await expect(response).rejects.toBeTruthy();
	});

swapnasundarbiswal avatar Jan 29 '20 09:01 swapnasundarbiswal

@swapnasundarbiswal Your code is not cover PointSvc.fetchData condition:

if (!resp.ok)
	throw new Error(resp.statusText);

viT-1 avatar Jan 29 '20 12:01 viT-1

I hit this same issue and found that the problem was with using expect.toThrow on an async function. I was able to get it working by using a try/catch in the test:

try {
  await PointSvc.fetchData({ label: 'anysearch' });
} catch (e) {
  expect(e.message).toEqual(statusText);
}

sbrudz avatar Jul 24 '20 20:07 sbrudz

@viT-1 I used

fetch.mockResponseOnce('{}', { status: 500, headers: { 'content-type': 'application/json' } });`
expect(await myFetchFunction()).toThrowError();

and that worked out.

tylervipond avatar Oct 15 '20 14:10 tylervipond

fetch.mockResponseOnce('{}', { status: 500, headers: { 'content-type': 'application/json' } });`
expect(myFetchFunction()).rejects.toThrow();

or

expect(myFetchFunction()).resolves.toThrowError();

Jest has built in functions to handle resolution or rejection of promises

yinzara avatar Oct 15 '20 15:10 yinzara

I was mistaken in my earlier comment: expect(await myFetchFunction()).toThrowError(); appears not to work (though it did initially, So I must've made a mistake elsewhere). I tried out expect(myFetchFunction()).resolves.toThrowError(); which appears to work but adds an error to the console while running tests:

(node:34701) UnhandledPromiseRejectionWarning: Error: expect(received).resolves.toThrowError()
Received promise rejected instead of resolved

expect(myFetchFunction()).rejects.toThrow(); seems to be exactly right!

tylervipond avatar Oct 15 '20 16:10 tylervipond