Open viT-1 opened 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();
});
@swapnasundarbiswal Your code is not cover PointSvc.fetchData condition:
if (!resp.ok)
throw new Error(resp.statusText);
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);
}
@viT-1 I used
fetch.mockResponseOnce('{}', { status: 500, headers: { 'content-type': 'application/json' } });`
expect(await myFetchFunction()).toThrowError();
and that worked out.
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
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!
jest-fetch-mock v3.0.1
Can't catch error =(
PointSvc.fetchData has code:
PointSvc.spec.ts:
Result:
Received function did not throw