Testing with node:test: Passing Suites, Failing Reports and Mocks
Test Node.js code with the built-in test runner and assert module: write tests and suites, read a real failing report with its expected and actual values, test async code and errors, and use a mock function, with the counts verified independently.
In this lesson you will
- Write tests with node:test and assert
- Test async code and errors
- Use a mock function
- Read a failing report
About 28 minutes
Trusting the totals
Mara’s tool now calculates what customers are charged, and a mistake costs money. Since version 18, Node.js has a test runner built in, so no extra package is needed: files that import node:test and node:assert are run with node –test, which finds files named like *.test.js, runs each test in order, and reports passes, failures and skips, and exits with a non-zero code when anything fails. A test is a function given a name with test(), or grouped with describe() and it(). Inside it you make assertions with node:assert, whose strict functions such as strictEqual and deepStrictEqual compare values without type coercion and, on failure, show the expected and actual values.
Three techniques cover most needs. For asynchronous code, a test may be an async function, and the runner waits for it; assert.rejects checks that a promise fails with the right error. For code that calls something expensive or unpredictable, such as sending an email, a mock function replaces it: mock.fn() records every call and its arguments, so a test can check that the function was called once with the right data without sending anything. And tests should be small, independent and named after behaviour, so that a failing name tells you what broke. The runner can print results in several reporters, including TAP, a simple text format that machines can read, which is what the example uses to count results.
| Need | Tool |
|---|---|
| Run all tests | node –test |
| A test | test(“name”, () => { … }) |
| Group | describe(“price”, () => { it(…) }) |
| Compare | assert.strictEqual(a, b), assert.deepStrictEqual(x, y) |
| Expect an error | await assert.rejects(promise, /message/) |
| Replace a function | const f = mock.fn() |
const fs = require('fs'), path = require('path'), os = require('os'), { spawnSync } = require('child_process');
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'tests-'));
const files = JSON.parse(process.argv[2]);
for (const [n, c] of Object.entries(files)) fs.writeFileSync(path.join(dir, n), c);
const r = spawnSync(process.execPath, ['--test', '--test-reporter=tap'], { cwd: dir, encoding: 'utf8' });
const out = r.stdout.replace(/duration_ms: [0-9.]+/g, 'duration_ms: 0').replace(/# duration_ms [0-9.]+/g, '# duration_ms 0');
const lines = out.split('\n');
const summary = lines.filter(l => /^# (tests|suites|pass|fail|cancelled|skipped|todo)/.test(l));
const results = lines.filter(l => /^\s*(ok|not ok) \d+ - /.test(l)).map(l => l.trim());
results.forEach(l => console.log(l));
console.log(summary.join(' | '));
const why = lines.filter(l => /^\s+(expected|actual|error):/.test(l)).map(l => l.trim());
console.log(why.join(' | '));
console.log('exit status of node --test:', r.status);
console.log('DATA ' + JSON.stringify({ status: r.status, summary, results, why }));
ok 1 - multiplies quantity by price
ok 2 - rejects zero quantity
ok 3 - rejects fractions
ok 1 - line totals
ok 1 - applies 10 percent from 100 items
ok 2 - does not apply below 100
ok 2 - discount
ok 3 - send calls the mailer once with the right message
ok 4 - send fails without an email
not ok 5 - a wrong expectation (this one fails on purpose)
ok 6 - work in progress # SKIP
# tests 9 | # suites 2 | # pass 7 | # fail 1 | # cancelled 0 | # skipped 1 | # todo 0
error: |- | expected: 950 | actual: 900
exit status of node --test: 1
exports.line = (qty, cents) => { if (!Number.isInteger(qty) || qty < 1) throw new RangeError('quantity must be a positive integer'); return qty * cents; };
exports.discount = (cents, qty) => qty >= 100 ? Math.round(cents * 0.9) : cents;
exports.send = async (mailer, order) => { if (!order.email) throw new Error('no email'); mailer(order.email, 'Order ' + order.id + ' received'); return true; };
const { test, describe, it, mock } = require('node:test');
const assert = require('node:assert/strict');
const { line, discount, send } = require('./price');
describe('line totals', () => {
it('multiplies quantity by price', () => assert.equal(line(3, 250), 750));
it('rejects zero quantity', () => assert.throws(() => line(0, 250), RangeError));
it('rejects fractions', () => assert.throws(() => line(1.5, 250), /positive integer/));
});
describe('discount', () => {
it('applies 10 percent from 100 items', () => assert.equal(discount(1000, 100), 900));
it('does not apply below 100', () => assert.equal(discount(1000, 99), 1000));
});
test('send calls the mailer once with the right message', async () => {
const mailer = mock.fn();
await send(mailer, { id: 7, email: 'ada@example.com' });
assert.equal(mailer.mock.callCount(), 1);
assert.deepEqual(mailer.mock.calls[0].arguments, ['ada@example.com', 'Order 7 received']);
});
test('send fails without an email', async () => { await assert.rejects(send(() => {}, { id: 8 }), /no email/); });
test('a wrong expectation (this one fails on purpose)', () => assert.equal(discount(1000, 100), 950));
test('work in progress', { skip: true }, () => {});
The script wrote the two files to a temporary folder and ran node –test there, with the TAP reporter so that the results are plain text. The runner found 9 tests in the file: 7 passed, 1 failed and 1 was skipped. The five calculation tests and the two async ones that passed cover the normal path and the boundaries: exactly 100 items gets the discount and 99 does not, a zero or fractional quantity throws a RangeError with the right message, and the email function calls its mock once with the right arguments. The mock replaced a real mailer, so no email was sent, and its recorded call showed that the function was called with “ada@example.com” and “Order 7 received”.
The failing test was deliberately wrong: it expected a discounted price of 950, but the function returns 900, which is 10 percent off 1,000. The report states it precisely, with the lines expected: 950 and actual: 900, so you do not have to guess which side is wrong. Because one test failed, node –test exited with status 1. A continuous integration service reads this status to stop a broken change from being published. Tests marked with skip are counted separately, so skipped work stays visible instead of silently disappearing.
Independent check: a separate count was made by reading the test file as text with a regular expression, counting the calls to it( and test(, and it found 9 tests, the same number as the runner’s own total, so no test was silently left out of the run. The summary line of the TAP output also satisfies the arithmetic: 7 passed + 1 failed + 1 skipped = 9, which is the number of tests.
Check by hand: 10 percent off 1,000 cents is 900. Nine tests are written in the file: three line-total tests, two discount tests, two async tests, one wrong expectation and one skipped test, which is 3 + 2 + 2 + 1 + 1 = 9. The two describe blocks are suites, not tests, so they are not counted among the nine, and the summary line reports two suites.
Break the code on purpose once, as this lesson did with a wrong expectation, to see that the test can fail. A test that cannot fail checks nothing.
Names such as “does not apply below 100” make a failing report readable on its own. Test the boundaries and the error cases first.
Every program in this lesson was run while the course was written, with Node.js 22 and only its built-in modules (plus the packages named in the lesson), and cross-checked with the shell, curl, Python or the specification. Node.js releases change, so check nodejs.org for the current long-term support version and its documentation. The test runner and its reporters are still evolving, so check the node:test documentation of your version. Frameworks such as Jest and Vitest offer more features with a similar style.
Practice
Add a test for a quantity of exactly 1. Use mock.fn with an implementation to simulate a mailer that throws, and test that send passes the error on. Run node –test with –test-name-pattern to select one test.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
How do you run the built-in tests?
- npm start
- node –test
- node test
- npx run
It finds *.test.js files.
What does assert.rejects check?
- That a promise fails with the expected error
- That a function returns
- That a file exists
- That a test is skipped
For async errors.
What does mock.fn() record?
- Every call and its arguments
- Network traffic
- File changes
- Timers
So tests can check calls.
What does a non-zero exit status of node –test mean?
- All passed
- Tests were skipped
- Node is old
- At least one test failed
CI reads it.
Why break a test on purpose once?
- To slow the suite
- To change the code
- It is required
- To prove that the test can fail
A test that cannot fail checks nothing.
Summary
- node –test runs *.test.js files with no extra package.
- assert.strictEqual and deepStrictEqual compare without coercion.
- Mocks record calls instead of doing the work.
- The exit status tells CI whether the suite passed.
Questions
Do I need Jest or Mocha?
Not for many projects: the built-in runner covers the basics. Others offer extra features such as snapshots and watch mode, so check what your team uses.
What is TAP?
The Test Anything Protocol: a simple text format for test results that many tools can read.
How many tests are enough?
Enough to change the code with confidence. Cover the rules that cost money or trust when they break, the boundaries and the failures.
