Capstone A: tests for the model and the storage
The tracker has two files worth testing and two that are covered by running them: the model decides what a task is, the storage decides what the file holds, and the commands are read from a session of the command line. The two test files of this lesson take a function each and call it with the values a user can reach, including the ones that must fail.
node:test is part of the runtime, so the project still has no dependency other than the linter. The lesson writes both files, runs them with the dot reporter and then breaks one expectation to show what a failing test prints.
The folder holds the manifest, the lint config, the model, the storage, the commands and the command line. This lesson adds the test folder and nothing else.
mkdir test
Tests of the model
Five cases cover the class. A valid task keeps its three fields and trims the title; a bad id throws a TaskError, and the second call in that test checks the message with a pattern; an empty title and a title over the limit are two calls in one test, because they are the same rule; the completed copy leaves the original alone; and a task that goes through JSON comes back equal to itself.
The last one is the test that pays for toJSON and fromJSON: deepEqual compares the prototypes as well as the fields, so the test would fail if the loader returned a plain object instead of a Task.
The file test/task.test.js:
vi test/task.test.js
const test = require('node:test');
const assert = require('node:assert/strict');
const { Task, TaskError } = require('../src/task');
test('a task keeps its three fields', () => {
const task = new Task(3, ' write the model ');
assert.equal(task.id, 3);
assert.equal(task.title, 'write the model');
assert.equal(task.done, false);
});
test('a task refuses an id that is not a positive integer', () => {
assert.throws(() => new Task(0, 'x'), TaskError);
assert.throws(() => new Task(1.5, 'x'), /positive integer/);
});
test('a task refuses an empty title', () => {
assert.throws(() => new Task(1, ' '), /non-empty/);
assert.throws(() => new Task(1, 'x'.repeat(61)), /60 characters/);
});
test('complete returns a new task and leaves the old one alone', () => {
const task = new Task(1, 'a');
const done = task.complete();
assert.equal(done.done, true);
assert.equal(task.done, false);
assert.notEqual(done, task);
});
test('a task survives the JSON round trip', () => {
const task = new Task(7, 'keep the order', true);
assert.deepEqual(Task.fromJSON(task.toJSON()), task);
});
A test name is a sentence, which is what the report prints when the test fails. The assert module is imported from node:assert/strict so that equal is the strict comparison; the lesson on assertions shows why the loose module is a trap.
Tests of the storage
A test of a file writes a file, so every test needs a folder of its own and a promise that the folder is removed whatever the test does. The helper at the top of the file does that with mkdtemp and a try and a finally, and each test is a function that receives the folder.
Five cases cover the two functions. A missing file is an empty list; what is saved comes back with its fields; the save leaves no temporary file; a file without a tasks array is refused with the message; and a file that is not JSON is refused with the error of the parser.
The file test/storage.test.js:
vi test/storage.test.js
const test = require('node:test');
const assert = require('node:assert/strict');
const { mkdtemp, readdir, rm, writeFile } = require('node:fs/promises');
const { tmpdir } = require('node:os');
const { join } = require('node:path');
const { Task } = require('../src/task');
const { load, save } = require('../src/storage');
async function withFolder(run) {
const folder = await mkdtemp(join(tmpdir(), 'tasks-test-'));
try {
await run(folder);
} finally {
await rm(folder, { force: true, recursive: true });
}
}
test('a missing file loads as an empty list', () =>
withFolder(async (folder) => {
assert.deepEqual(await load(join(folder, 'tasks.json')), []);
}));
test('what is saved comes back with its fields', () =>
withFolder(async (folder) => {
const file = join(folder, 'tasks.json');
const tasks = [new Task(1, 'one'), new Task(2, 'two', true)];
assert.equal(await save(file, tasks), 2);
assert.deepEqual(await load(file), tasks);
}));
test('the write leaves no temporary file', () =>
withFolder(async (folder) => {
const file = join(folder, 'tasks.json');
await save(file, [new Task(1, 'one')]);
assert.deepEqual(await readdir(folder), ['tasks.json']);
}));
test('a file without a tasks array is refused', () =>
withFolder(async (folder) => {
const file = join(folder, 'tasks.json');
await writeFile(file, '{"version": 1}\n');
await assert.rejects(load(file), /no tasks array/);
}));
test('a broken file keeps the error of JSON', () =>
withFolder(async (folder) => {
const file = join(folder, 'tasks.json');
await writeFile(file, 'not json\n');
await assert.rejects(load(file), SyntaxError);
}));
assert.rejects is the asynchronous cousin of assert.throws: it takes the promise and the same second argument, a class or a pattern. A test that awaited the call without an assertion would pass whatever happened, so the two refusals are the tests that hold the error path of the loader.
readdir is the assertion about the rename. A save that wrote tasks.json directly would pass every other test in the file and fail this one, which is the point of testing the folder rather than the return value.
The run and the dot reporter
node --test finds every file in the folder that ends with .test.js and runs the tests of each one. The dot reporter prints a character per test and no name, no duration and no path, which is why the block below is the same on every machine and on every run.
node --test --test-reporter=dot
echo "the exit status: $?"
npx eslint .
echo "the lint status: $?"
..........
the exit status: 0
the lint status: 0
Ten dots for ten tests, a zero for the test runner and a zero for the linter, which prints nothing when the folder is clean. The last two lines are the whole check that a commit hook would run, and the statuses are what it would read.
A test that fails
One wrong expectation is enough. The first test of the model compares the title with 'wrote the model' instead of the trimmed 'write the model', and the runner reports the case, the assertion and the two values.
vi test/task.test.js
node --test --test-reporter=dot
echo "the exit status: $?"
.....X....
Failed tests:
✖ a task keeps its three fields
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected
+ 'write the model'
- 'wrote the model'
the exit status: 1
The cross sits at the position of the failing test, so a reader can count the tests before it. The block above is the real report with the duration of the test and the stack frames left out: the frames name a path of this machine and the duration changes with every run, and neither tells a reader anything about the failure. The two lines with a sign are the difference that the assertion prints for two strings.
The exit status is one, which is what a pipeline reads. A test that fails and a program that throws are the same signal to everything around them, and the difference is the report: the runner names the test that failed and stops after running the rest, while a thrown error stops the program at the first one.
Exercises
- Add a test for a title of exactly 60 characters. Which boundary does it pin, and which one does the existing test leave open?
- Remove the finally from the helper and make a test throw. What is left in the folder, and why does the system temporary folder fill up?
- Write a test for complete() that checks the id and the title as well as the flag. How many assertions does it need?
- Save two tasks with the same id and load them again. Does the storage refuse the file, and which function would be the right place for that check?
- Run the tests with the default reporter and compare the output with the dot reporter. Which two kinds of information disappear, and which one is only noise?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which command runs the tests of the project?
Answer
node --test
The runtime finds the test files itself, and the reporter decides how the result is printed.
-
What does this program print?
console.log(typeof [], typeof {});Answer
object object
An array is an object, so typeof does not tell the two apart; Array.isArray does.
-
Why does every test of the storage get a folder of its own?
Answer
So two tests cannot see or delete each other's files
The tests then run in any order and none of them depends on what an earlier one wrote.
-
What does this program print?
const fs = require("node:fs"); try { fs.readFileSync("/no/such/file"); } catch (error) { console.log(error.code); }Answer
ENOENT
The code is the short name of the failure, and a missing file is ENOENT.
-
What happens when one test of a file fails?
Answer
That test fails, the others still run, and the exit status is not zero
The runner reports every test, and one failure is enough to make the status a failure.
-
What does this program print?
const assert = require("node:assert/strict"); try { assert.equal(2 + 2, 5); } catch (error) { console.log(error.code); }Answer
ERR_ASSERTION
A failed assertion is its own kind of error, and its code says so.
-
Why does the block of the failing test leave the stack frames out?
Answer
A frame names a path of the machine and says nothing about the failure
The report of a failure is the test name and the difference of the two values.
-
What does this program print?
const names = ["a", "b", "c"]; console.log(names.map((name) => name.length).join(""));Answer
111
Every name has one character, and the three results are joined into one string.
-
What does
assert.rejectscheck?Answer
That a promise rejects, with a class or a pattern as the reason
It is the asynchronous form of assert.throws and takes the same second argument.
-
What does this program print?
const assert = require("node:assert/strict"); assert.deepEqual({ a: [1, 2] }, { a: [1, 2] }); console.log("same contents");Answer
same contents
The two objects have the same fields and the same array, so the deep check passes.
The programs and commands on this page were run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container. The block of the failing test is the real report with its duration and its stack frames left out.
Article author: Arthur Isaev