Node.js Test Runner
Below is a clear and complete guide on the Node.js Test Runner, introduced officially in Node.js v18+ as a built-in testing framework β no external packages required.
π Node.js Test Runner (Built-in Testing Framework)
Node.js now includes a native test runner so you can write tests without Jest, Mocha, or any other library.
Import from:
Or using ES Modules:
β 1. Create Your First Node.js Test
π sum.js
π sum.test.js
Run test:
β 2. Asynchronous Tests
Supports async/await:
β 3. Test Suites (Subtests)
Use nested tests:
β 4. Running a Specific Test File
β 5. Using Test Hooks (Before / After)
β 6. Skipping Tests
β 7. Todo Tests
β 8. Mocking & Spying (built-in)
Node.js has its own mocking API:
β 9. Test Reporter Options
To see full output:
Available reporters:
-
tap -
spec -
json -
junit
Example:
β 10. Assertions API
Node.js Test Runner uses node:assert, including:
Example:
β 11. Testing ES Modules
Run:
β 12. Folder Structure
Node automatically detects files named:
-
*.test.js -
test-*.js -
inside
/testfolder
β 13. Comparison: Node Test Runner vs Jest vs Mocha
| Feature | Node Test Runner | Jest | Mocha |
|---|---|---|---|
| Built-in | β Yes | β | β |
| Zero config | β | β | β |
| Mocking | β built-in | β | β (need Sinon) |
| Snapshot Testing | β | β | β |
| API Testing | β (with fetch + assert) | β | β |
| Speed | Very Fast | Fast | Slower |
| Best For | Backend Node apps | Full-stack apps | Enterprise backend |
π― When to Use Node.js Test Runner?
Use it when:
β You want minimal dependencies
β You want very fast tests
β You work mostly on backend / APIs
β You prefer native Node.js tools
β You donβt need React/Jest-specific features
