Pure function unit tests
What you need to know
A pure function depends only on its explicit inputs and returns a result without changing external state. Extracting validation and access-policy decisions into pure functions makes edge cases inexpensive to test.
By the end, you can: define deterministic input and output; test boundary cases.
Parse a bounded page number
function parsePage(raw:unknown){ if(typeof raw!=='string'||!(/^[1-9][0-9]*$/).test(raw))return 1; const n=Number(raw); return Number.isSafeInteger(n)&&n<=50&&String(n)===raw?n:1;}console.log(parsePage('3'),parsePage('51'),parsePage(['2','3']));Expected behavior: 3 1 1. Repeated values and invalid inputs fall back to page 1.
How it works
A test contract defines input domain, expected output and invalid cases. For example, a requested page number may be absent, malformed, repeated or outside the supported range. Write the expected result before implementing the function. Arrange inputs, act by invoking the function, and assert a meaningful result. Include valid interior values and boundary cases, not just one happy path. Test that arrays or objects supplied by callers are not mutated when the contract requires immutability. Node's built-in test runner and strict assertions are sufficient for independent functions; Vitest and Jest are alternatives when project tooling calls for them. A unit test does not execute Next.js navigation, caches or authorization middleware. A passing policy test also does not prove that a Route Handler calls that policy before a write.
An independent unit test
// test-page.cjs; run beside the compiled contractconst {test}=require('node:test');const assert=require('node:assert/strict');const {parsePage}=require('./contracts.js');test('last allowed page',()=>assert.equal(parsePage('50'),50));test('reject repeated parameter',()=>assert.equal(parsePage(['2','3']),1));Expected behavior: Both assertions pass if the function follows the documented contract. This is not a framework test.
Common mistake
Do not use a test that asserts only that a function returned something. A permissive implementation might pass that assertion while accepting invalid inputs.
Practice and verification
Implement the staged page parser exercise and check zero, leading zero, a repeated parameter, the upper boundary and a very large number. Then test a plausible wrong solution.
Scope: Proposed Next.js 16.x / React 19, Cache Components disabled unless noted. Framework, browser and component examples are staged; local standalone tests are reported separately. Exact dependency patches and platform contracts pending.