Test invariants and the real application
Test the promises that must remain true across state changes, requests, rendering and failure recovery.
What you will be able to do
- Choose tests from invariants and failure risks.
- Separate pure logic, component, integration and E2E coverage.
- Test actual async Server Component behavior in a running application.
- Avoid brittle assertions that only mirror implementation details.
Start with what must never become false
An invariant is a statement that should hold across allowed operations. Cart totals equal the sum of accepted line items. A user cannot edit another tenant's document. A stale search response cannot replace the newest query. Writing these statements before tests clarifies what the implementation is protecting and which examples can disprove it.
A test is valuable when a realistic bug makes it fail. A test that simply repeats the same formula using the same helper may agree with a broken implementation. Choose examples from boundaries, alternate orderings and denied requests. Include at least one negative case for each security or concurrency invariant instead of relying on the happy path.
Use the smallest level that proves the promise
Pure unit tests suit parsers, reducers, key factories and permission policies. Component tests verify labels, keyboard interactions and visible states around those functions. Integration tests exercise a handler and its storage or service contract. E2E tests verify actual routes, navigation, server rendering and mutation behavior through the browser.
Current Next.js Vitest guidance does not support async Server Components as ordinary component unit tests and recommends E2E for those cases. Mocking the component into a synchronous function does not prove RSC, cache or hydration behavior. Keep small logic tests fast, then use a running Next.js build for framework boundaries that a DOM-only environment cannot reproduce.
Assert user outcomes and boundary results
Prefer roles and accessible names in browser tests so assertions also exercise the interface contract. Wait for a meaningful state, response or URL instead of sleeping for an arbitrary duration. Check both the user-visible result and the server-side effect when a mutation or authorization boundary matters. A toast can appear even when a write silently failed.
The following Playwright example is a pattern to adapt to actual accessible names in the lab. It is intentionally not presented as a test already executed for that project. Its purpose is to show a direct route visit, an observable search interaction and a URL assertion that can survive CSS changes.
Terminal command
import { test, expect } from "@playwright/test";
test("search remains shareable after reload", async ({ page }) => {
await page.goto("/catalog");
await page.getByRole("searchbox", { name: "Search products" }).fill("pen");
await page.getByRole("button", { name: "Search", exact: true }).click();
await expect(page).toHaveURL(/q=pen/);
await page.reload();
await expect(page.getByRole("searchbox", { name: "Search products" })).toHaveValue("pen");
});Control the failure you want to observe
To test a search race, make the earlier request resolve after the later request. To test recovery, return a specific failure and then a success. To test authorization, create two identities with distinct records and issue a forbidden request. Deterministic fixtures make these cases explainable; random sleeps produce intermittent evidence.
Use mocks at a boundary when they isolate the question, but document what they replace. A mocked database cannot prove a real unique constraint or transaction. A mocked fetch response cannot prove a deployment proxy preserves streaming. Include a small number of integration checks for those actual contracts when the task depends on them.
Report exactly what ran
A validation report should name the environment, command, cases and remaining limits. Passing unit tests for a cache-key function does not verify Next.js caching. A successful development page does not verify a production build. A local browser check does not verify deployment. Keep these claims separate so the next engineer knows what evidence still needs collecting.
For interview practice, introduce a deliberate defect after the solution works: remove a tenant predicate, accept a stale event or drop a query parameter. Confirm that the intended test catches it, then restore the correct code. This demonstrates that the tests protect an actual behavior rather than simply increasing a coverage percentage.
Misconceptions to replace
Compare the tempting shortcut with the model you can verify in code.
- CLAIM TO CHALLENGEHigh coverage guarantees the important behavior is correct.
- A more accurate model
Assertions must detect realistic defects; coverage only identifies executed code.
- How to check it
Introduce a missing tenant predicate and verify the intended test fails.
- CLAIM TO CHALLENGEA success toast proves a mutation persisted.
- A more accurate model
Check the durable result and permission boundary as well as the UI feedback.
- How to check it
The lesson separates component outcomes from integration persistence evidence.
Mistakes to catch in your own code
- Testing an async Server Component only through a mocked synchronous render.
- Using fixed sleeps instead of observable conditions.
- Checking only a toast while ignoring the persisted result.
- Calling local checks production verification.
Write it by hand
JavaScript logic playground
Summarize invariant evidence
Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.
- Input is {required,results}; required is a list of invariant IDs and results contains {invariant,status} with status pass, fail or blocked.
- For each required invariant, fail takes precedence over blocked, blocked over pass, and no result becomes missing.
- Return sorted arrays {passed,failed,blocked,missing}. Ignore results for unrequested invariants.
Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.
Inspect 3 test cases
- Do not hide a failure behind a pass
Input
{ "required": [ "auth" ], "results": [ { "invariant": "auth", "status": "pass" }, { "invariant": "auth", "status": "fail" } ] }Expected
{ "passed": [], "failed": [ "auth" ], "blocked": [], "missing": [] } - Keep missing and blocked separate
Input
{ "required": [ "render", "cache", "keyboard" ], "results": [ { "invariant": "render", "status": "pass" }, { "invariant": "cache", "status": "blocked" } ] }Expected
{ "passed": [ "render" ], "failed": [], "blocked": [ "cache" ], "missing": [ "keyboard" ] } - Ignore unrelated evidence and deduplicate
Input
{ "required": [ "url", "url" ], "results": [ { "invariant": "other", "status": "fail" }, { "invariant": "url", "status": "pass" } ] }Expected
{ "passed": [ "url" ], "failed": [], "blocked": [], "missing": [] }
Reveal the worked solution and reasoning
function solve(input) {
const output = { passed: [], failed: [], blocked: [], missing: [] };
for (const id of [...new Set(input.required)].sort()) {
const statuses = input.results.filter(item => item.invariant === id).map(item => item.status);
if (statuses.includes("fail")) output.failed.push(id);
else if (statuses.includes("blocked")) output.blocked.push(id);
else if (statuses.includes("pass")) output.passed.push(id);
else output.missing.push(id);
}
return output;
}Evidence aggregation must not turn blocked or failed behavior into success.
The function assesses only supplied records; it cannot establish that a reported test really ran.
Use exact commands and artifacts in a real verification report.
Verify it in a real Next.js application
Next.js application lab
Use the shipped test matrix and make a test fail deliberately
Open the local application route /catalog after starting the workbench. Follow the experiment and collect the evidence described below.
Make the change
- Read tests/domain.test.ts and tests/session-token.test.ts, then run npm test in the project. These existing Node tests cover cart/query/title/redirect contracts and jose token verification.
- Build the project, install a Playwright browser, and run npm run test:e2e. Inspect tests/browser/workbench.spec.ts for URL persistence, modal navigation, hydration, actions, tenant denials, version conflicts, cache invalidation, streaming, recovery and both session models.
- In a separate project copy, run node scripts/challenge.mjs and npm test. The command saves the domain solution and installs intentionally incomplete functions. Implement one contract at a time and use --solution only when you deliberately want to replace your attempt.
- Introduce one known defect into your practice copy, confirm that the relevant existing test fails, then repair it. For example, remove a task-version comparison or make cart restoration accept a negative price.
- Implementation extension: add missing coverage for idempotency replay, task validation feedback, automatic cross-tab coordination or your own new feature. If choosing component tests, install and configure that test environment; an async Server Component still needs the real application path.
Check the behavior
- Each executed test can fail on a meaningful contract violation; an untouched assertion or an unexecuted test file is not verification.
- Browser checks target a built running Next.js project, and the report states whether Playwright reused an existing server or started one.
- The challenge copy begins with failing domain tests and your implementation makes the relevant cases pass without consulting the solution first.
- The report separates pure fixtures, unit/token tests, runtime browser checks and any blocked or unexecuted extensions.
Review the application reasoning
The inline kata classifies evidence only. The project contains actual test files and commands, but their presence does not establish that a particular learner environment, adapter or deployment passed them.
Open the project files and run instructions
A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.
The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.
cd nextjs-interview-lab
npm ci
npm run dev
# In a second terminal
npm test
# Stop dev, then verify the production application
npm run build
npm start
# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2eOpen http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.
Explain it in an interview
Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.
01What invariant would you test in a Next.js cart?
I would state that the displayed total equals the sum of confirmed quantities times unit prices, quantities remain within permitted bounds, and rejected operations do not erase unrelated accepted changes.
I would test the pure reducer for those rules, then test the real form or action path for pending, rejection and successful persistence. Each test level proves a different part of the promise.
Follow-up questions
- Which test catches a stale rollback?
- Would a snapshot test prove the arithmetic?
- Vitest with Next.jsOfficial documentation
- Playwright with Next.jsOfficial documentation
02How would you test an async Server Component?
I would unit-test its pure helpers and integration-test its data contract, then use E2E against the running Next.js application for actual async rendering and navigation. Current official Vitest guidance recommends E2E for async components.
I would not claim a mocked DOM render verifies RSC transport, cache invalidation or hydration. Those depend on the framework runtime.
Follow-up questions
- What belongs in a unit test instead?
- Should the E2E run against dev or a production build?
- Vitest with Next.jsOfficial documentation
- Playwright with Next.jsOfficial documentation
03How do you make an async race test deterministic?
I control completion order with deferred responses or a test server: issue A, issue B, resolve B, then resolve A. The assertion is that B remains visible.
This targets the stale-response bug directly. Waiting a random number of milliseconds makes the test dependent on machine load and may never exercise the problematic ordering.
Follow-up questions
- How do you test cancellation after completion?
- What if the component unmounts before either response?
- Playwright with Next.jsOfficial documentation
04Does high code coverage prove correctness?
No. Coverage shows which code executed, not whether assertions can detect the important wrong outcomes. A weak test can execute every line and miss a tenant leak.
I combine coverage information with boundary cases, negative tests and deliberate bug injection. I report the concrete behaviors verified rather than a percentage alone.
Follow-up questions
- What defect would you inject to evaluate a permission test?
- Which production behavior still needs integration evidence?
- Vitest with Next.jsOfficial documentation
- Playwright with Next.jsOfficial documentation
Check your understanding
Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.
Your checkpoint
Loading your local progress.
Sources and further reading
- Vitest with Next.jsOfficial documentation
- Playwright with Next.jsOfficial documentation
- Data securityOfficial documentation
- Error handlingOfficial documentation