Mocking & Stubs
Mock modules, functions, and HTTP with Jest and Mock Service Worker.
Mock Functions
jest.fn() stubs callback props and spies on module exports. Assert call arguments and return mockResolvedValue for async child components.
Inject mocks via props dependency injection pattern—easier than module mock for presentational components.
const onSave = jest.fn();
render(<Editor onSave={onSave} />);
await user.click(screen.getByRole("button", { name: /save/i }));
expect(onSave).toHaveBeenCalledWith({ title: "Draft" });Mock Modules
jest.mock("next/navigation") common in Next.js app router tests. Factory returns mocked useRouter, useSearchParams.
Mock heavy child components only when testing parent orchestration—not when integration value matters.
jest.mock("./api", () => ({
fetchUser: jest.fn(() => Promise.resolve({ name: "Ada" })),
}));Mock Service Worker (MSW)
MSW intercepts fetch at network level—realistic loading states without mocking fetch manually. setupServer for Node tests; setupWorker for browser.
handlers array defines GET/POST responses; server.use overrides per test.
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
const server = setupServer(
http.get("/api/user", () => HttpResponse.json({ name: "Ada" }))
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());Module Mocking Pitfalls
jest.resetModules when cache pollution between tests. Partial mock with jest.requireActual spread preserves unmocked exports.
Over-mocking creates false positives—integration test with real child catches prop drilling bugs module mocks hide.
- MSW 2.x uses http and HttpResponse API
- Align mock response shape with TypeScript types
- Test error responses 500 and network failure paths
What to Mock
Mock at boundary: HTTP, localStorage, Date, random, analytics. Do not mock React itself or RTL queries.
next/image, next/link may need test doubles documented in framework guides.
- Use real react-router MemoryRouter wrapper instead of mocking Link
- vi.mock is Vitest equivalent with same structural patterns
- Document standard mocks in test-utils for team consistency