ReactEasy

Unit vs Integration testing?

Unit tests check one small piece in isolation, such as a function, reducer or hook, usually with its dependencies mocked. Integration tests check that several pieces work together, such as a page component with its child components, state, router and a mocked API, the way a user would use them. In React, integration-style component tests usually give the most confidence per test.

Unit tests

  • Targets: utilities (formatPrice), reducers, validation schemas, custom hooks, pure components.
  • Fast, precise failure messages, easy to write.
  • Risk: heavily mocked tests can pass while the real integration is broken.

Integration tests

  • Targets: a form submitting to a mocked API and showing the result; a page with routing, data fetching and context.
  • Use React Testing Library with real child components, real providers, and MSW to mock the network instead of mocking modules.
  • Slower than unit tests but much more realistic.

End-to-end tests (for completeness)

Full app in a real browser with a real or staging backend (Playwright). The most confidence, the slowest and most brittle.

Balance: the "testing trophy"

Kent C. Dodds' model for front-end testing: a base of static checks (TypeScript, ESLint), some unit tests, mostly integration tests, and a few E2E tests for critical flows.

Tips

  • Mock at the boundary (network) rather than inside your own code.
  • Name tests by behavior: "shows an error when the card is declined".
  • Keep tests independent; reset MSW handlers and query caches between tests.

Code example

tsx
1// Unit: a pure reducer
2import { expect, test } from "vitest";
3import { cartReducer } from "./cart-reducer";
4
5test("adds an item", () => {
6 expect(cartReducer({ items: [] }, { type: "added", id: "pen" })).toEqual({ items: [{ id: "pen", qty: 1 }] });
7});
8
9// Integration: page + children + data fetching + mocked network (MSW)
10import { render, screen } from "@testing-library/react";
11import { http, HttpResponse } from "msw";
12import { setupServer } from "msw/node";
13import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
14import { ProductsPage } from "./products-page";
15
16const server = setupServer(http.get("/api/products", () => HttpResponse.json([{ id: "1", name: "Pen" }])));
17beforeAll(() => server.listen());
18afterAll(() => server.close());
19
20test("lists products from the API", async () => {
21 render(
22 <QueryClientProvider client={new QueryClient()}>
23 <ProductsPage />
24 </QueryClientProvider>
25 );
26 expect(await screen.findByText("Pen")).toBeInTheDocument();
27});

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app