Part 17 / Stage 5
Testing and quality
Goal: Install a real Vitest + React Testing Library suite into this harness, test a Server Action and a data-access function for real against the QuickCart capstone's own code, and — just as importantly — hit and honestly document the places this toolchain genuinely cannot reach (an
asyncServer Component, and a module that only works inside Next's own request runtime). Finish by wiring lint, type-check, and test into one local "is this safe to merge" command. Time: ~6 h · Level: finished Stage 4 (QuickCart working,npm run build/npm run lintclean inharness/) Verified against: Next.js 16.4.6 / React 19.3.0 (unchanged), Vitest 4.1.12,@testing-library/react16.3.3,@testing-library/jest-dom7.0.1,@testing-library/user-event14.6.13,@vitejs/plugin-react6.3.0,jsdom31.0.1,vite-tsconfig-paths6.1.1 — all installed for real intoharness/, every transcript below captured by actually runningnpm run test,npm run lint,npm run typecheck, andnpm run buildagainst this install.
What you will learn
- Why this part pins Vitest to the
V4npm dist-tag (4.1.12), not thelatesttag, and the exact evidence behind that call - Two real import-time failures a Next.js codebase hits under a generic Vitest config — a
server-onlymodule throwing on import, and a module chain that readsprocess.envbefore.env.localhas been loaded — and the fix for each, reproduced before and after - Testing a data-access function (
app/quickcart/lib/products.ts) the plain way: call it, read the real SQLite-backed result - Testing a Server Action (
addToCartAction/removeFromCartAction) by mocking exactly three Next.js modules (next/headers,next/cache,next/navigation) and nothing else — testing this course's own logic, not Next's request plumbing - Testing a Client Component (
AddToCartCounter) with React Testing Library, including a real "multiple elements found" failure from a missing cleanup step - Honestly flagged, not worked around: the installed Next.js docs' own stated limit — "Vitest currently does not support [async Server Components]" — reproduced here with the real React error, not just quoted
- Wiring
npm run lint,npm run typecheck, andnpm run testinto one command a human (or, later, CI) can treat as a merge gate
Topics in this part
Practice
Every exercise below edits a real file inside harness/ (vitest.config.mts
or one of the three test files this part added) and says exactly what to
change. Restore the file to its original state before moving to the next
exercise — git diff harness/ (if you're tracking the harness in git the
way this course's own repo does) is the fastest way to confirm you actually
put it back.
Exercise 1: Reproduce the server-only import failure yourself
Scenario: Section 2's README quotes the real error from removing the server-only alias, but doesn't walk you through reproducing it. Do it yourself, end to end.
What to do: In harness/vitest.config.mts, delete (or comment out) the "server-only": fileURLToPath(...) line inside resolve.alias. Run npm run test -- app/quickcart/lib/products.test.ts. Read the real error. Restore the line and confirm the test passes again.
Sample output (run for real against this harness):
$ npm run test -- app/quickcart/lib/products.test.ts # alias removed
FAIL app/quickcart/lib/products.test.ts [ app/quickcart/lib/products.test.ts ]
Error: This module cannot be imported from a Client Component module. It should only be used from a Server Component.
❯ Object.<anonymous> node_modules/server-only/index.js:1:7
💡 Hint: The error fires from inside node_modules/server-only/index.js itself, before any of products.ts's own code runs — confirming it's server-only's own exports map resolving to the throwing branch, not a bug in this course's test. Restoring the alias line fixes it immediately, with no other change needed.
Exercise 2: Reproduce the missing-SESSION_PASSWORD failure yourself
Scenario: Section 3 showed this failure coming from two hops away in the import graph (actions.ts → auth.ts → session.ts → session-config.ts). Confirm it's really the loadEnv call in vitest.config.mts that prevents it, not something inside actions.test.ts itself.
What to do: In harness/vitest.config.mts, comment out the loadEnv(...) line and the for (const [key, value] of ...) loop that copies it into process.env. Run npm run test -- app/quickcart/actions.test.ts. Restore both lines afterward.
Sample output (run for real against this harness):
$ npm run test -- app/quickcart/actions.test.ts # loadEnv lines removed
FAIL app/quickcart/actions.test.ts [ app/quickcart/actions.test.ts ]
Error: SESSION_PASSWORD is not set — see harness/README's Part 15 setup note.
❯ app/account/lib/session-config.ts:21:9
💡 Hint: products.test.ts never imports anything from app/account/, so it's unaffected by this change — only actions.test.ts fails, because actions.ts imports requireUser from ../account/lib/auth even though neither addToCartAction nor removeFromCartAction (the two actions this part's tests actually call) uses it. Importing a module runs its whole dependency graph's top-level code, whether or not the specific function you're testing needs all of it.
Exercise 3: Removing a product that was never in the cart is a safe no-op
Scenario: removeFromCartAction's test in examples/03-cart-actions.test.ts only covers removing a product that is in the cart. Confirm the DAL's DELETE ... WHERE cart_id = ? AND product_id = ? behaves safely when there's no matching row at all — no error, no change to anything else in the cart.
What to do: Add a new test to app/quickcart/actions.test.ts (or a scratch copy) that adds p1 to a test cart, then calls removeFromCartAction for a different product id (p4) that was never added, and asserts p1 is still in the cart afterward with its original quantity.
Sample output (run for real against this harness):
$ npm run test -- app/quickcart/actions.test.ts
Test Files 1 passed (1)
Tests 5 passed (5)
💡 Hint: removeStatement.run(cartId, productId) (in lib/cart.ts) returns an info.changes of 0 when no row matched — better-sqlite3's own documented behavior for a DELETE that matches nothing, not an error. removeFromCartAction never checks info.changes at all, which is fine here: deleting zero rows and deleting one row both leave the rest of the cart exactly as it was.
Exercise 4: Reproduce both React Testing Library gotchas from section 6, in order
Scenario: Section 6 found two separate real failures in the same file — missing afterEach(cleanup), then (after fixing that) a missing @testing-library/jest-dom/vitest import. Reproduce both, one at a time, in a scratch copy.
What to do: Copy harness/app/store/_components/AddToCartCounter.test.tsx to a scratch file in the same directory. First remove only the afterEach(cleanup) line (keep the jest-dom import) and run it. Restore that line, then remove only the import "@testing-library/jest-dom/vitest"; line and run it again. Delete the scratch file when done.
Sample output (run for real against this harness, two separate runs):
$ npm run test -- app/store/_components/<scratch>.test.tsx # afterEach(cleanup) removed
Found multiple elements with the role "button" and name "Increase quantity"
$ npm run test -- app/store/_components/<scratch>.test.tsx # afterEach(cleanup) restored, jest-dom import removed
Error: Invalid Chai property: toHaveTextContent
💡 Hint: The first failure only shows up once a second test renders — the first test in the file always passes on its own, since there's nothing stale to collide with yet. The second failure is unrelated to cleanup entirely — toHaveTextContent simply isn't registered on Vitest's expect without the jest-dom import, so it fails on the very first expect(...).toHaveTextContent(...) call regardless of cleanup.
Exercise 5: Reproduce the async-Server-Component limit yourself, then find it in your own capstone
Scenario: Section 7 reproduced the installed docs' stated Vitest limit with a tiny scratch component. Confirm the same failure happens with one of this harness's real page-level components, not just a toy example.
What to do: Pick any real async function component in this harness that isn't the default export of a route file (an unexported inner component like CartContents in app/quickcart/cart/page.tsx works, once temporarily exported). Write a scratch test that imports and renders it directly with React Testing Library, the same way examples/05-async-server-component-probe.tsx does. Run it, read the real error, then revert your temporary export and delete the scratch test.
Sample output (run for real against this harness, exporting CartContents from cart/page.tsx temporarily). The first attempt used an assertion that passed, and printed nothing — a real, separate finding: Vitest only shows a test's captured stdout/stderr when that test fails, confirmed by rerunning with a deliberately wrong assertion just to force the output visible:
$ npm run test -- app/quickcart/cart/<scratch>.test.tsx
stderr | <CartContents> is an async Client Component. Only Server Components can be async at the moment. ...
💡 Hint: The error message names your real component (CartContents), not the generic AsyncGreeting from the README's probe — confirming this isn't a quirk of the toy example, it's the same real limit hitting a real part of this course's own capstone. This is exactly why section 7 says, plainly, that none of QuickCart's page-level Server Components are unit-testable with this toolchain.
Next
Part 18: Deployment and observability
Show the solutions for Part 17 (5 files)
solutions/ex01.md
# Solution to Exercise 1
`vitest.config.mts`, with the alias commented out:
```ts
resolve: {
alias: {
// "server-only": fileURLToPath(new URL("./node_modules/server-only/empty.js", import.meta.url)),
},
},
```
**Run for real against this harness:**
```text
$ npm run test -- app/quickcart/lib/products.test.ts
FAIL app/quickcart/lib/products.test.ts [ app/quickcart/lib/products.test.ts ]
Error: This module cannot be imported from a Client Component module. It should only be used from a Server Component.
❯ Object.<anonymous> node_modules/server-only/index.js:1:7
Test Files 1 failed (1)
```
Restoring the alias line and rerunning:
```text
$ npm run test -- app/quickcart/lib/products.test.ts
Test Files 1 passed (1)
Tests 3 passed (3)
```
The failure happens before any line of `products.ts` runs — the stack trace's only frame inside this project is `node_modules/server-only/index.js:1:7`, the package's own throw statement, confirming the alias (not something inside `products.ts` or `products.test.ts`) is what makes this work.
solutions/ex02.md
# Solution to Exercise 2
`vitest.config.mts`, with the `loadEnv` lines commented out:
```ts
// const env = loadEnv("test", process.cwd(), "");
// for (const [key, value] of Object.entries(env)) {
// process.env[key] ??= value;
// }
```
**Run for real against this harness:**
```text
$ npm run test -- app/quickcart/actions.test.ts
FAIL app/quickcart/actions.test.ts [ app/quickcart/actions.test.ts ]
Error: SESSION_PASSWORD is not set — see harness/README's Part 15 setup note.
❯ app/account/lib/session-config.ts:21:9
Test Files 1 failed (1)
```
```text
$ npm run test -- app/quickcart/lib/products.test.ts # unaffected
Test Files 1 passed (1)
Tests 3 passed (3)
```
Restoring the two `loadEnv` lines and rerunning `actions.test.ts`:
```text
$ npm run test -- app/quickcart/actions.test.ts
Test Files 1 passed (1)
Tests 4 passed (4)
```
`products.test.ts` never fails either way — it never imports anything under `app/account/`, so `session-config.ts`'s top-level `if (!password) throw ...` never runs for that file at all. This is the exact import-graph distinction the hint in the exercises file names: importing `actions.ts` pulls in `requireUser` (used only by `placeOrderAction`, a function neither of this part's two Server-Action tests calls), and that one unused import is still enough to run `session-config.ts`'s top-level code and throw.
solutions/ex03.md
# Solution to Exercise 3
Added to `app/quickcart/actions.test.ts`, inside the existing `describe` block:
```ts
test("removeFromCartAction is a safe no-op for a product never in the cart", async () => {
await expect(addToCartAction(cartForm("p1", 2))).rejects.toThrow(MockRedirect);
await removeFromCartAction(cartForm("p4")); // never added — no throw expected
const lines = getCartLines(testCartId);
expect(lines).toHaveLength(1);
expect(lines[0]).toMatchObject({ productId: "p1", quantity: 2 });
});
```
**Run for real against this harness:**
```text
$ npm run test -- app/quickcart/actions.test.ts
Test Files 1 passed (1)
Tests 5 passed (5)
```
`lib/cart.ts`'s `removeStatement` is `DELETE FROM cart_items WHERE cart_id = ? AND product_id = ?` — a `DELETE` with a `WHERE` clause that matches zero rows is not an error in SQL (or in `better-sqlite3`'s own API: `.run()` just returns `{ changes: 0, ... }`). `removeFromCartAction` doesn't check `changes` either way, and this test confirms that's fine: `p1`'s row, unrelated to the `p4` delete attempt, is still there afterward with its original quantity untouched.
solutions/ex04.md
# Solution to Exercise 4
**Step 1 — `afterEach(cleanup)` removed, `jest-dom` import kept:**
```text
$ npm run test -- app/store/_components/<scratch>.test.tsx
FAIL app/store/_components/<scratch>.test.tsx > AddToCartCounter > + and − buttons change the quantity, floored at 1
Found multiple elements with the role "button" and name "Increase quantity"
❯ app/store/_components/<scratch>.test.tsx:XX:YY
```
Only the **second** test in the file fails this way — the first test's `render()` call is still the only thing mounted in `document.body` at that point, so `getByRole` only ever finds one match there. By the time the second test calls `render()` again, the first test's tree is still attached (nothing unmounted it), so the exact same query now matches two buttons with the same accessible name, one from each render.
**Step 2 — `afterEach(cleanup)` restored, `import "@testing-library/jest-dom/vitest";` removed:**
```text
$ npm run test -- app/store/_components/<scratch>.test.tsx
FAIL app/store/_components/<scratch>.test.tsx > AddToCartCounter > starts at quantity 1 and shows no 'added' message yet
Error: Invalid Chai property: toHaveTextContent
❯ app/store/_components/<scratch>.test.tsx:XX:YY
```
This time it's the **first** test that fails, on its very first `expect(...).toHaveTextContent(...)` call — `toHaveTextContent` is a matcher `@testing-library/jest-dom` adds to Vitest's `expect`; without importing the package's `vitest` entry point, Vitest's underlying Chai assertion library has never heard of it, and reports it as an unknown ("Invalid") property rather than running it.
Both fixes restored together (the real state of `examples/04-add-to-cart-counter.test.tsx`):
```text
$ npm run test -- app/store/_components/AddToCartCounter.test.tsx
Test Files 1 passed (1)
Tests 3 passed (3)
```
solutions/ex05.md
# Solution to Exercise 5
`app/quickcart/cart/page.tsx`, `CartContents` temporarily exported:
```ts
export async function CartContents() { // was: async function CartContents()
const cartId = await getCartId();
...
}
```
Scratch test, `app/quickcart/cart/scratch-cartcontents.test.tsx`:
```tsx
import { render, screen } from "@testing-library/react";
import { expect, test } from "vitest";
import { CartContents } from "./page";
test("probe: CartContents is an async Server Component", () => {
// @ts-expect-error
render(<CartContents />);
console.log("BODY:", document.body.innerHTML);
expect(document.body.innerHTML).toBe("FORCE_FAIL_TO_SHOW_OUTPUT"); // deliberately wrong, see below
});
```
**First run, with a trivially-true assertion instead of the deliberately-wrong one above — printed nothing at all, even though the warning still fired internally:**
```text
$ npm run test -- app/quickcart/cart/scratch-cartcontents.test.tsx
Test Files 1 passed (1)
Tests 1 passed (1)
```
That's a real, separate finding: Vitest only shows a test's captured `stdout`/`stderr` for a **failing** test. Rerunning with the deliberately-wrong assertion above (just to force the output to print) shows the real warning was there all along:
```text
$ npm run test -- app/quickcart/cart/scratch-cartcontents.test.tsx
stdout | BODY: <div></div>
stderr | <CartContents> is an async Client Component. Only Server Components can be async at the moment. ...
stderr | A component suspended inside an `act` scope, but the `act` call was not awaited. ...
Test Files 1 failed (1)
AssertionError: expected '<div></div>' to be 'FORCE_FAIL_TO_SHOW_OUTPUT'
```
The error names `CartContents` by its real name, confirming this is the exact same unsupported case as the README's generic `AsyncGreeting` probe, hitting a real page component from this course's own capstone rather than a contrived toy. The temporary `export` on `CartContents` and the scratch test file were both reverted/deleted afterward — `git diff harness/app/quickcart/cart/page.tsx` showed no changes once restored.
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Installing vitest unpinned and expecting it to "just work" with an existing Next.js @types/node pin |
The current latest dist-tag (5.1.2) requires @types/node@^22, a real ERESOLVE conflict with create-next-app's own ^20 default — reproduced in section 1 |
Check npm view vitest dist-tags and pick the newest dist-tag actually compatible with this project's existing pins (V4 → 4.1.12 here), the same evidence standard DESIGN-NOTES.md already uses |
Assuming a file that starts with import "server-only" can just be imported in a test like any other module |
server-only's own exports map throws under the "default" condition Vitest resolves with — reproduced in section 2, not a hypothetical |
Alias server-only to its own empty.js in vitest.config.mts's resolve.alias |
Assuming .env.local is available to a test the same way it is to next dev |
Next loads it itself; Vite/Vitest do not, for plain process.env reads — reproduced in section 3 as a real two-hops-away import failure |
Call Vite's own loadEnv() in vitest.config.mts and copy the result into process.env before tests run |
Calling cookies()/headers()/redirect() directly in a test, unmocked, and expecting it to behave like a stub |
These are backed by Next's request-scoped AsyncLocalStorage, which doesn't exist outside an actual request — reproduced directly with node -e in section 5 |
Mock next/headers/next/cache/next/navigation at the module boundary; test this course's own logic, not Next's plumbing |
Forgetting afterEach(cleanup) (or test.globals: true) with React Testing Library under a Vitest config that sets globals: false |
Nothing unmounts the previous test's render; a later getByRole can match more than one element across two mounted copies — reproduced as a real "multiple elements found" failure in section 6 |
Import cleanup from @testing-library/react and call it in an explicit afterEach |
Reaching for toHaveTextContent/toBeInTheDocument without importing @testing-library/jest-dom's matcher registration |
These aren't built into Vitest's expect — reproduced as Invalid Chai property: toHaveTextContent in section 6 |
import "@testing-library/jest-dom/vitest" once, at the top of any test file using these matchers |
Trying to unit-test a page.tsx or any other async function Component() directly with Vitest + RTL |
The installed docs state this plainly and section 7 reproduces the real React error (<X> is an async Client Component. Only Server Components can be async at the moment.) — this is a documented limit, not a config mistake to fix |
Extract testable logic into a plain (non-component) function, and/or cover the async component itself with E2E tests (Playwright, not attempted in this course) |
Quick recap
- Vitest is pinned to the
V4dist-tag (4.1.12), notlatest(5.1.2), becauselatestneeds@types/node@^22and this harness is pinned to^20— checked withnpm view vitest dist-tags, the same evidence standard every other dependency choice in this course uses, and it broughtnpm auditfrom one critical + one moderate finding down to 0 vulnerabilities. - Two Next.js-specific import-time gotchas had to be fixed in
vitest.config.mtsbefore any test involving this course's own code could even load:server-onlythrowing under the default module resolution condition, and.env.localnot being loaded intoprocess.envthe waynext devloads it. - A pure data-access function (
products.ts) is the easiest thing in this stack to test — no mocking needed at all. - Testing a Server Action means mocking exactly
next/headers,next/cache, andnext/navigation— testing this course's own logic (quantity floors, unknown-product guards, which path revalidates) rather than Next's own request plumbing. - Testing a Client Component works the ordinary React Testing Library way, with two real gotchas under this config: missing
afterEach(cleanup)(stale DOM across tests) and missing the@testing-library/jest-dom/vitestmatcher import. - The one thing this toolchain genuinely cannot do: unit-test an
asyncServer Component. Reproduced directly against this install, matching the installed docs' own stated limit exactly — not worked around, because there is no honest workaround short of E2E tests or restructuring the component to extract testable logic.
Checklist
- I installed Vitest pinned to the
V4dist-tag, notlatest, and can state why in terms of this harness's@types/nodepin - I reproduced the
server-onlyimport failure myself (temporarily remove thevitest.config.mtsalias, rerunnpm run test, restore it) - I reproduced the
.env.local/SESSION_PASSWORDfailure myself (temporarily remove theloadEnvlines, rerun, restore them) - I ran the real data-access test (
products.test.ts), the real mocked-Server-Action test (actions.test.ts), and the real component test (AddToCartCounter.test.tsx) and read all ten passing assertions, not just the summary line - I reproduced the missing-
cleanup/"multiple elements found" failure and the missing-jest-dom-import failure myself, in that order, before looking at the fixes - I reproduced the async-Server-Component failure myself (section 7's scratch probe) and can quote the real React error, not just the installed docs' warning
- I ran
npm run lint && npm run typecheck && npm run test && npm run buildback to back and got a clean exit on all four