How do you mock API calls in component tests?

React testing, accessibility and TypeScript · Freshers and experienced

Model answer

Use Mock Service Worker (MSW) to intercept network requests at the network level, so components use real fetch code and you only fake the server. You can also mock a module with vi.mock or jest.mock. Reset handlers between tests.

Network-level mocking tests more of the real code path than mocking the fetch function itself.

Learn this topic

Testing React Apps with Vitest and React Testing Library in the course React.js Full Course: Beginner to Advanced.

Sign in to add your own answer.

More questions