The previous lesson in this module gave you a four-file layout, where the rules sit in files that import nothing at all. That separation only pays off if you can check that the rules still behave the way you expect after every change, and that is what this lesson is about. Testing JavaScript means answering one question about a piece of code, which is whether it still does what it is supposed to do. A test is a small program that runs your function with known inputs and fails loudly when the answer is not what you expected. None of it needs a framework, and the first useful test suite takes about twenty minutes to write.
The previous lesson in this module covered "Organizing a Script Without a Framework", and the next lesson in this module is about "Capstone: A Persistent To-Do App in Plain JavaScript".
What is a test, in plain terms?
Three parts. There is a name that describes the behaviour, there is an input, and there is the answer you expect. "Adding two prices returns their sum in cents" is a name. 1999 and 350 are the inputs, and 2349 is the expected answer. When the code returns something else, the test fails and tells you which case broke.
The point of the name is that it survives a change to the code. If it said "tests the add function", it would tell you nothing once you renamed the function. If it says "adds prices in cents", then a failure tells you that adding prices in cents is broken, which is exactly what you want to know at two in the morning.
How do you write your first assertion?
You compare the actual result with the expected one and print a line either way. That is the whole mechanism, and you can write it in five lines before you install anything at all.
let failures = 0;
function check(label, actual, expected) {
const same = JSON.stringify(actual) === JSON.stringify(expected);
if (!same) {
failures += 1;
}
const status = same ? 'PASS ' : 'FAIL ';
const extra = same ? '' : ' -> got ' + JSON.stringify(actual);
console.log(status + label + extra);
}
function double(n) {
return n * 2;
}
function evenNumbers(numbers) {
const result = [];
for (const number of numbers) {
if (number % 2 === 0) {
result.push(number);
}
}
return result;
}
check('doubles a number', double(21), 42);
check('adds prices in cents', 1999 + 350, 2349);
check('keeps the even numbers', evenNumbers([1, 2, 3, 4]), [2, 4]);
console.log(failures === 0 ? 'all checks passed' : failures + ' check(s) failed');
The output is:
PASS doubles a number
PASS adds prices in cents
PASS keeps the even numbers
all checks passed
The failures counter is what makes this useful in practice. A test file that only prints is easy to ignore, and easy to ignore means that it quietly stops matching reality. Keep the counter, print a summary line at the end, and set a failing exit status so that the file can be run from a script.
Comparing with JSON.stringify works for arrays and objects as well as for single values, which is why it beats the === operator for anything that is not a simple value.
How do you organise a test file?
You keep one file per area of the code, with the tests for a module sitting next to it in a tests folder. Node ships with a small test runner built in, so a test file looks like a normal module that calls a test function for each case. The two imports below are the only extra pieces that you need, and they come from Node itself.
import test from 'node:test';
import assert from 'node:assert/strict';
function double(n) {
return n * 2;
}
test('doubles a number', function () {
assert.equal(double(21), 42);
});
test('waits before it answers', async function () {
const value = await Promise.resolve('ready');
assert.equal(value, 'ready');
});
Run it with the test runner and the plain-text reporter:
node --test --test-reporter=tap
The output lists one line per test and a summary at the end:
TAP version 13
# Subtest: doubles a number
ok 1 - doubles a number
---
duration_ms: 3.8123
type: 'test'
...
# Subtest: waits before it answers
ok 2 - waits before it answers
---
duration_ms: 0.655
type: 'test'
...
1..2
# tests 2
# suites 0
# pass 2
# fail 0
# cancelled 0
# skipped 0
# todo 0
# duration_ms 309.3598
The millisecond figures change on every run, and the pass and fail counts are the part that matters. A failing test prints not ok instead of ok, shows the values that did not match, and points at the line where the comparison failed.
Two details in that file are worth copying. The test names describe behaviour rather than function names. And the second test is marked async, which is all it takes to test a function that returns a promise.
How do you test code that waits?
You mark the test function as async, you await the promise inside it, and you assert on the value that came back. The runner waits for your test to finish, so a promise that never settles shows up as a timeout instead of a silent pass.
async function fetchRecord(id) {
await new Promise(function (resolve) {
setTimeout(resolve, 10);
});
return { id: id, name: 'record ' + id };
}
async function check(label, actual, expected) {
const same = JSON.stringify(actual) === JSON.stringify(expected);
console.log(same ? 'PASS ' : 'FAIL ');
console.log(label);
}
async function main() {
const record = await fetchRecord(7);
await check('the record comes back with its id', record.id, 7);
await check('the record comes back with a name', record.name, 'record 7');
}
main();
The output is:
PASS
the record comes back with its id
PASS
the record comes back with a name
There are two things to avoid here. Never write a test that depends on the wall clock, because a slow machine will fail it for no reason at all. Control the timing yourself, with a fake clock or an injected delay. And never assert inside a callback that the test does not await, because the test will finish before the assertion ever runs.
How do you test a function that reaches outside itself?
You give it the outside world as an argument. A function that sends a message should accept the sender, so that the test can pass in a fake one and watch what it received.
function createNotifier(send) {
return async function (message) {
await send(message);
return 'sent: ' + message;
};
}
async function main() {
const sent = [];
const notify = createNotifier(async function (message) {
sent.push(message);
});
const result = await notify('hello');
console.log('the sender received:', JSON.stringify(sent));
console.log('the notifier reported:', result);
}
main();
The output is:
the sender received: ["hello"]
the notifier reported: sent: hello
Nothing was sent anywhere. The fake sender collected the message in an array, and the test can now check that array. This is the same dependency injection that keeps the files in the previous lesson apart, and it is what makes a function testable in the first place.
Keep the fake as simple as the contract allows. If the real sender returns a ticket number, then the fake should return one too. If the fake has to grow a second method, a second argument, and a configuration object, then the design is asking too much of the test, and the function is probably doing too much work.
How do you avoid testing the wrong thing?
Test the behaviour that a caller can observe, and not the steps that your function happens to take. A test that checks a private helper, a specific array order inside a function, or the exact wording of a log line will break every time you change the code, and then the team will start ignoring the whole suite.
| Worth a test | Not worth a test |
|---|---|
| A rule that turns input into output | The order two independent statements run in |
| A calculation with a known answer | The exact wording of a log message |
| The awkward case: empty list, bad input, zero | A library or framework you did not write |
| A bug you fixed, so it stays fixed | The private helper a function happens to call |
One test per behaviour is a good default. If a test name needs the word "and", then it is probably two tests, and the first failure will not tell you which half broke.
Testing habits worth keeping
- Name every test after the behaviour it protects, in plain words.
- Start with the awkward inputs, such as an empty list, zero, a negative number, or the wrong type, because that is where the bugs live.
- Check what the caller sees, and not the steps the code takes internally.
- Give anything that reaches outside the program a fake that you can inspect.
- Keep the suite fast enough that you run it before every commit instead of after a bug.
- When a test fails, read the message first, because it should tell you what was expected and what actually arrived.
Try it yourself: Take the rule file from the previous lesson and write a test file for it with four cases. Adding a to-do gives it the next id, adding an empty title throws, marking a missing id throws, and filtering by open returns only the unfinished ones. Run it once and confirm that all four cases pass. Then break the rule on purpose by making the next id always 1, and confirm that the suite fails with a message that points at the wrong id. Finally, add a fifth case for a title with spaces around it, and check that the stored title is trimmed.
The next lesson in this module is the capstone, where all of the pieces from this module come together in one small application.