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:

node --test

⭐ 2. Asynchronous Tests

Supports async/await:



 


⭐ 3. Test Suites (Subtests)

Use nested tests:


 


⭐ 4. Running a Specific Test File

node --test tests/math.test.js

⭐ 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:

node --test --test-reporter spec

Available reporters:

  • tap

  • spec

  • json

  • junit

Example:

node --test --test-reporter=junit > report.xml

⭐ 10. Assertions API

Node.js Test Runner uses node:assert, including:



 

Example:



 


⭐ 11. Testing ES Modules



 

Run:

node --test

⭐ 12. Folder Structure



 

Node automatically detects files named:

  • *.test.js

  • test-*.js

  • inside /test folder


⭐ 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

You may also like...