How do you mock a fetch call in Jest tests?
deterministic network mocking.
replace global fetch with a Jest mock or a library like jest-fetch-mock, return a resolved Promise with a fake Response, and reset mocks between tests.
WHAT THIS TESTS: The ability to isolate a component from the network so tests are fast, deterministic, and cover async states.
A GOOD ANSWER COVERS: The goal is to intercept fetch so no real request goes out. The simplest approach assigns global.fetch to a jest.fn that returns a resolved Promise yielding a fake Response object with a json method returning your fixture data. A library such as jest-fetch-mock streamlines this, letting you call mockResponseOnce with JSON and automatically restoring fetch. In the test you arrange the mocked response, render the component with React Native Testing Library, and then use an async query like findByText or waitFor to assert the UI after the Promise resolves, since state updates happen asynchronously. You reset or clear mocks in beforeEach to prevent leakage between tests, and you add cases for rejected Promises and non-ok responses to cover error and loading branches.
COMMON WRONG ANSWERS: Letting the test hit a live endpoint, making it slow and flaky. Asserting synchronously before the fetch Promise resolves and the component re-renders. Forgetting to reset the mock, so one test's response bleeds into another. Mocking the component's internals instead of the network boundary.
LIKELY FOLLOW-UPS: How to test loading and error states, the difference between mocking fetch and mocking a higher-level API module, why MSW is an alternative, and how act and waitFor relate.
ONE CONCRETE EXAMPLE: A Profile component fetches user data on mount. The test sets fetch to resolve once with a user fixture, renders Profile, then awaits findByText with the user's name to confirm it appears. A second test makes fetch reject and asserts an error message renders, with jest.clearAllMocks in beforeEach keeping them independent.
Read the original → github.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.