jefflau / jest-fetch-mock

Jest mock for fetch
MIT License
883 stars 116 forks source link

How to check raising error by !response.ok ? #149

Open viT-1 opened 4 years ago

viT-1 commented 4 years ago

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

swapnasundarbiswal commented 4 years ago

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();
    });
viT-1 commented 4 years ago

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

if (!resp.ok)
    throw new Error(resp.statusText);
sbrudz commented 4 years ago

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);
}
tylervipond commented 3 years ago

@viT-1 I used

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

and that worked out.

yinzara commented 3 years ago
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

tylervipond commented 3 years ago

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!