Course map
Stage 1: App Router Foundations
Stage 2: The Rendering Model
Stage 3: Data, Caching and Mutations
Stage 4: Full-Stack Next.js
Stage 5: Production and Specialization

Part 17 / Topic 6 of 8

Testing a Client Component: AddToCartCounter

AddToCartCounter (app/store/_components/AddToCartCounter.tsx, Part 6) is the installed docs' own "currently supported" case stated plainly: a synchronous, "use client" component with no await, no Server Component boundary at all. examples/04-add-to-cart-counter.test.tsx renders it with React Testing Library and drives it with @testing-library/user-event. The first run of this file, before a cleanup step existed, failed exactly like this:

$ npm run test -- app/store/_components/AddToCartCounter.test.tsx
 ❯ getMultipleElementsFoundError
 ❯ app/store/_components/AddToCartCounter.test.tsx:34:29
     34|     await user.click(screen.getByRole("button", { name: "Increase quan…
Found multiple elements with the role "button" and name "Increase quantity"

This config sets test.globals: false (explicit imports everywhere, no ambient expect/afterEach) — which also means React Testing Library's own automatic per-test DOM cleanup never registers, because that automatic hook relies on a global afterEach existing. Every earlier render() call's output was still mounted in the same jsdom document.body when the next test rendered a second copy. Fix: afterEach(cleanup), imported explicitly from @testing-library/react, at the top of the file. A second real failure showed up immediately after that fix, from a different cause — toHaveTextContent isn't a real Chai/Vitest matcher on its own:

Error: Invalid Chai property: toHaveTextContent

@testing-library/jest-dom's matchers (toHaveTextContent, toBeInTheDocument, ...) have to be registered onto Vitest's expect — the package ships a ready-made @testing-library/jest-dom/vitest entry point for exactly this, imported once at the top of the test file (examples/04-add-to-cart-counter.test.tsx, first line). With both fixes in place:

$ npm run test -- app/store/_components/AddToCartCounter.test.tsx
 Test Files  1 passed (1)
      Tests  3 passed (3)

Done here? The practice set for Part 17 — including the solutions — is on the part page.

Search the guide