Write and run tests with node:test
Write a test with node:test and node:assert, run it with node --test, read the failure diff, and see which file names the runner finds.
You have a small module, say a slugify function, and you want one test for it. Installing Jest or Vitest and writing their config is more setup than the function itself. Node has shipped a stable test runner since Node 20: node:test gives you test(), node:assert gives you the checks, and node --test runs them.
Write the module and its test
In an empty directory, add a package.json containing {"type": "module"} so Node treats the example's .js files as ES modules. Save this as slugify.js.
export function slugify(title) {
return title.toLowerCase().replace(/[^a-z0-9]+/g, '-')
}This version turns surrounding punctuation and spaces into dashes too. Save the two checks next to it as slugify.test.js.
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { slugify } from './slugify.js'
test('lowercases and joins words with dashes', () => {
assert.equal(slugify('Hello World'), 'hello-world')
})
test('trims punctuation at the ends', () => {
assert.equal(slugify(' Ship it! '), 'ship-it')
})Each test() takes a name and a function. If the assertion throws, the runner marks the test as failed. In strict assertion mode, assert.equal compares with Object.is() and shows a diff on failure.
Run it and read the failure
Run node --test --test-reporter=spec from the project folder. You should see one failure in the reporter output.
✔ lowercases and joins words with dashes
✖ trims punctuation at the ends
ℹ tests 2
ℹ pass 1
ℹ fail 1
✖ failing tests:
test at slugify.test.js:9:1
✖ trims punctuation at the ends
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected
+ '-ship-it-'
- 'ship-it'The second test points at its line, shows the value it got after + and the one it wanted after -, and the process exits with code 1, so a CI job fails.
Append .replace(/^-|-$/g, '') to the existing chain to remove the leading and trailing dash. Run the same command again to see ℹ pass 2 and exit code 0. To run it as npm test or pnpm test, set "test": "node --test" in the scripts of package.json.
While you fix one case, node --test --test-name-pattern="trims" runs only the tests whose name matches.
When it finds zero tests
With no arguments, node --test searches the current folder and below for file names it treats as tests: *.test.js, *-test.js, *_test.js, test-*.js, test.js, and JavaScript files under a test folder. All of these patterns also accept .mjs and .cjs extensions. A file named slugify.spec.js next to the module matches none of them.
If that is your only test file, the spec reporter prints ℹ tests 0 and Node exits 0. Rename the file, or name it on the command line: node --test slugify.spec.js. Node 21 and later also take a quoted glob, node --test "**/*.spec.js", and Node expands it instead of your shell.