How to Use Node Test Runner in Node.js: Simple Guide
Use the built-in
node:test module in Node.js by importing it and writing test functions with test(). Run your test file with node --test to execute tests and see results in the console.Syntax
The Node.js test runner uses the test() function to define tests. You import it from the node:test module. Each test has a name and a callback function where you write assertions.
Assertions are made using the assert module to check if values meet expectations.
javascript
import test from 'node:test'; import assert from 'node:assert'; test('test name', () => { assert.strictEqual(actual, expected); });
Example
This example shows a simple test that checks if 2 + 2 equals 4 using the Node.js test runner.
javascript
import test from 'node:test'; import assert from 'node:assert'; test('simple addition test', () => { const result = 2 + 2; assert.strictEqual(result, 4); });
Output
1 test passed
Common Pitfalls
Common mistakes include forgetting to import test or assert, not running tests with node --test, or writing asynchronous tests without handling promises properly.
Also, avoid using console.log for test results; rely on assertions instead.
javascript
/* Wrong: Missing import and running with plain node */ // test('fail test', () => { // assert.strictEqual(1, 1); // }); /* Right: Import and run with node --test */ import test from 'node:test'; import assert from 'node:assert'; test('pass test', () => { assert.strictEqual(1, 1); });
Quick Reference
- Import test and assert:
import test from 'node:test'; import assert from 'node:assert'; - Define tests:
test('name', () => { ... }) - Run tests: Use
node --test yourfile.js - Assertions: Use
assert.strictEqual()and other assert methods
Key Takeaways
Use the built-in node:test module with test() to write tests in Node.js.
Run tests using the command node --test yourfile.js to see results.
Always import both test and assert modules before writing tests.
Write clear assertions with assert.strictEqual() to verify behavior.
Avoid running test files with plain node; use the --test flag.