An example of how you could mock the fetch() function:
/// abc.test.js
window.fetch = jest
.fn(() => (
Promise.resolve({
ok: true,
json: () => {count: 1}
})
));By doing this, anytime any function makes a call to fetch(), Jest will run the mocked version above instead, returning a mock result object.
Taking this one step further:
/// abc.test.js
window.fetch = jest
.fn()
.mockImplementationOnce(() =>
Promise.resolve({
ok: true,
json: () => {count: 1},
})
)
.mockImplementationOnce(() =>
Promise.resolve({
ok: false,
status: 404,
statusText: "Not Found",
})
);Doing this allows us to test for different fetch result cases (success and failure).