1. Concept library
  2. Web Dev with React
  3. Module 10: Testing components

Concept

Mocking network calls

Tests should not hit a real server. Intercept requests at the network layer, with a tool such as MSW, so the component code under test runs unchanged and each test controls the responses it gets.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain why tests should intercept at the network layer
  2. Set up MSW handlers for a success and an error response
  3. Spot the module mock that skips the request code

In practice

A few lines that show Mocking network calls doing its job.

TSX
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";

const server = setupServer(
  http.get("/api/users/7", () => HttpResponse.json({ id: "7", name: "Ada" })),
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

test("shows the user", async () => {
  render(<UserPage id="7" />);
  expect(await screen.findByText("Ada")).toBeInTheDocument();
});

The common mistake

Watch for

Mocking the module that calls fetch instead of the network. The test then no longer exercises the request code, the parsing or the error handling, which is where the bugs are.

What to know first

Your roadmap puts these before Mocking network calls, unless you already know them.

How it stays learned

Once a session shows you understand Mocking network calls, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled
Previous in the module← Querying by role