Organize test suites, fixtures and cleanup
Quick answer
A test runner discovers or executes named tests, reports results and provides lifecycle hooks. Use predictable setup and teardown so each test can run independently.
How it works
With Node v22.16.0, import test from node:test and run node --test file.test.cjs. A test can register cleanup using context.after; suite hooks beforeEach and afterEach can set up or dispose state. Avoid sharing mutable fixtures unless intentionally testing shared behavior. Use fresh input records for each test. Do not rely on test execution order or exact TAP timing text. The examples illustrate fixture construction and cleanup mechanics; actual test runner hooks are tested in the project.
Local examples
Run in Node.js v22.16.0 as a CommonJS script. No interactive debugger attached; actual ByteMind editor support is unverified.
(async () => {const fixture=()=>({rows:[]});const a=fixture(),b=fixture();a.rows.push("x");console.log(a.rows.length,b.rows.length);})()Expected console output:
1 0Separate fixture instances isolate changes.
Run in Node.js v22.16.0 as a CommonJS script. No interactive debugger attached; actual ByteMind editor support is unverified.
(async () => {const log=[];try{try{log.push("work");throw new Error("x");}finally{log.push("cleanup");}}catch{log.push("caught");}console.log(log.join(","));})()Expected console output:
work,cleanup,caughtCleanup runs even when the work throws before the outer catch handles it.
Common mistakes
Do not assume prior tests initialized the data you need. Do not swallow an assertion failure in a cleanup block.
Practice
Run the capstone test file twice and verify its individual test count and zero failures each time.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Organize test suites, fixtures and cleanup — Knowledge Check
Apply the concept and reason about local example output.
Why use a fixture factory for mutable test data?
Which command runs a specific Node test file?
Why register cleanup with the test context?
What is the exact console output in Organize test suites, fixtures and cleanup example 1?
(async () => {const fixture=()=>({rows:[]});const a=fixture(),b=fixture();a.rows.push("x");console.log(a.rows.length,b.rows.length);})()What is the exact console output in Organize test suites, fixtures and cleanup example 2?
(async () => {const log=[];try{try{log.push("work");throw new Error("x");}finally{log.push("cleanup");}}catch{log.push("caught");}console.log(log.join(","));})()