Part 17 / Topic 5 of 8
Testing a Server Action: mocking next/headers, next/cache, next/navigation
addToCartAction/removeFromCartAction (QuickCart's own Server Actions, Part 12's pattern) call cookies() (via getOrCreateCartId), revalidatePath, and — on the add path — eventually redirect. Section 3 already showed that just importing this file's dependency graph can throw outside a request scope; calling cookies() itself is worse — reproduced directly, standalone, with no mocking at all:
$ node -e "require('next/headers').cookies().catch(e => console.log('ERR', e.message))"
ERR `cookies` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context
cookies()/headers()/redirect() are all backed by Next's own request-scoped AsyncLocalStorage, which only exists while next dev/next start is actually handling a real HTTP request — Vitest never creates that scope, and nothing short of actually running the server does. The fix mocks exactly those three modules (examples/03-cart-actions.test.ts) and nothing else — a fake Map-backed cookie jar for next/headers, a vi.fn() spy for revalidatePath, and a redirect() that throws a recognizable MockRedirect sentinel (mirroring how the real redirect() also works by throwing a control-flow signal the router catches) so a test can assert which path a Server Action redirected to:
$ npm run test -- app/quickcart/actions.test.ts
Test Files 1 passed (1)
Tests 4 passed (4)
Everything these four tests actually exercise is this course's own code — the real addToCart/removeFromCart DAL functions, the real quantity-flooring logic (Math.max(1, ...)), the real "unknown product id" guard — running against the real SQLite file, with a disposable, uniquely-named test cart cleaned up in afterEach. Nothing about Next's router, Next's cookie-signing, or Next's redirect mechanics is being tested here, and that's the point: those are Next's job to get right, not this course's capstone's.
Done here? The practice set for Part 17 — including the solutions — is on the part page.