how to write test case for fetch in react code example
Example: how to test fetch
function mockFetch(data) {
return jest.fn().mockImplementation(() =>
Promise.resolve({
ok: true,
json: () => data
})
);
}
test('fetchPerson()', async () => {
fetch = mockFetch(someJson); // or window.fetch
const person = await fetchPerson('whatever id');
expect(person).toEqual(someJson);
// Make sure fetch has been called exactly once
expect(fetch).toHaveBeenCalledTimes(1);
});