I have a fetch call and unit test for that fetch all. It was working, suddenly i see that unit test cases failed for API unit testing. Below is my code
React fetch call
export const getUser = async () => {
try {
const resp = await fetch(url);
return resp.json();
} catch (err) {
throw new Error(err);
}
};
Unit test case
const mockResp = {};
const mockJsonPromise = Promise.resolve(mockResp);
const mockFetchPromise = Promise.resolve({
json: () => mockJsonPromise,
});
jest.spyOn(global, "fetch").mockImplementation(() => mockFetchPromise);
test("test getUser", (done) => {
expect(getUser()).toEqual(mockFetchPromise);
global.fetch.mockClear();
done();
});
Error - UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with reason "Error: TypeError: Cannot read properties of undefined (reading 'json')"