Challenge 3: How a Leaked Handler Breaks an Unrelated Test — Possible Solution
====================================================================
CONCRETE SCENARIO: imagine a test file with two tests, run in this
order:
it("shows an error message when the profile request fails", async () => {
server.use(http.get("/api/user", () => HttpResponse.error()));
render();
expect(await screen.findByText("Could not load profile")).toBeInTheDocument();
});
it("shows the user's name on a successful load", async () => {
render();
expect(await screen.findByText("Ada")).toBeInTheDocument();
});
If afterEach(() => server.resetHandlers()) is MISSING, the server.use()
override from the FIRST test — making /api/user always return an
error — remains active for every test that runs afterward in the same
file, since MSW handlers registered via server.use() persist until
explicitly reset.
WHAT HAPPENS TO THE SECOND TEST: it renders UserProfile expecting a
normal, successful load, and asserts that "Ada" eventually appears.
But because the error-simulating handler from the FIRST test is still
active, the actual request still fails — "Ada" never appears, and
screen.findByText("Ada") eventually times out and the test fails.
WHY THIS IS CONFUSING TO DIAGNOSE: nothing in the SECOND test's own
code mentions errors, server.use(), or the first test at all — it
looks like a perfectly ordinary, unrelated success-path test that has
simply, mysteriously started failing. A developer investigating would
likely start by suspecting UserProfile's own success-path code, or
the second test's own assertions — not immediately realize the real
cause lives in a DIFFERENT test, earlier in the file, that "leaked" its
setup forward. This is exactly why this chapter's warn-box calls this
out specifically: the FAILURE shows up somewhere that gives no direct
clue about where the actual MISTAKE (a missing reset) was made.