Sub topic 11
Testing the core logic
This chapter assumes you have the wcl project from the earlier chapters: a tsconfig.json that compiles src to dist, a pure countText function in src/count.ts, and a main function in src/cli.ts that returns an exit code. You should know async/await and be comfortable running npm scripts. No test framework is needed. Node.js ships one, node:test.
Why the logic was separated
The previous chapter moved the counting rules into countText, a function that takes a string and returns numbers. It reads no files, writes no output, and never touches process. That is what makes it cheap to test: you call it with a string and compare the result. A test needs no temporary files and no mocks, and it can't leave state behind.
The entry point is the opposite. It reads process.argv, talks to the file system, and sets an exit code. You can still test it, but the tests are slower and coarser. A good suite has many fast tests of pure functions and a few tests that run the real command.
The node:test runner
node:test is built into Node.js 18 and later. You import test and register a callback. If the callback throws, the test fails. If it returns normally, or its promise resolves, the test passes. Assertions come from node:assert/strict, whose comparisons are strict by default. assert.deepEqual in that module compares object contents with strict equality, so { lines: 2 } does not match { lines: "2" }.
Here is the starting test file from the plan, saved as src/count.test.ts:
import { test } from "node:test";
import assert from "node:assert/strict";
import { countText } from "./count.js";
test("counts lines and words", () => {
assert.deepEqual(countText("a b\nc\n"), { lines: 2, words: 3 });
});
test("empty input has no lines or words", () => {
assert.deepEqual(countText(""), { lines: 0, words: 0 });
});Two details matter here. The import path ends in .js even though the source file is count.ts. With module: "NodeNext", TypeScript requires the extension that will exist at run time, and it resolves ./count.js to ./count.ts while type checking. The test file is also part of src, so tsc compiles it to dist/count.test.js alongside everything else.
Running the tests
The test script in package.json compiles first and then runs the compiled output:
{
"scripts": {
"build": "tsc",
"test": "tsc && node --test dist"
}
}Run it with npm test. The && matters. If tsc reports a type error, the shell stops and the tests don't run. Type errors in a test file therefore fail the build, which is usually what you want.
The runner prints one line per test and a summary with passed, failed, and skipped counts. If any test fails, node --test exits with a non-zero code, so CI systems treat the run as failed.
Choosing cases: the edge cases of counting
Two tests don't prove much. The value of a test suite comes from the inputs where a wrong implementation would give a different answer. For countText, the interesting cases come from how lines and words are defined:
- Empty text has zero lines, not one.
"".split("\n")returns[""], which has length 1, so the function special-cases it. - A trailing newline ends the last line. It doesn't start a new one. That is why
countTextsubtracts 1 whentext.endsWith("\n"). - A final line without a newline still counts.
- A lone
"\n"is one line with zero words. - Blank lines in the middle count as lines.
- Runs of spaces and tabs separate words but don't create empty words, which is why the code filters out empty strings.
- Windows line endings (
\r\n) should not add words.\ris whitespace, so\s+absorbs it.
Each of these goes into a test, and each test name states the rule it checks. A failing name such as "a trailing newline does not add a line" tells you what broke before you open the file.
Table-driven tests
When many cases share the same shape, put them in an array and register one test per row. The test name comes from the row, so a failure points to a specific case.
import { test } from "node:test";
import assert from "node:assert/strict";
import { countText } from "./count.js";
interface Case {
name: string;
input: string;
expected: { lines: number; words: number };
}
const cases: Case[] = [
{ name: "empty input", input: "", expected: { lines: 0, words: 0 } },
{ name: "single line without newline", input: "a b", expected: { lines: 1, words: 2 } },
{ name: "last line without newline", input: "a b\nc", expected: { lines: 2, words: 3 } },
{ name: "trailing newline does not add a line", input: "a b\nc\n", expected: { lines: 2, words: 3 } },
{ name: "lone newline", input: "\n", expected: { lines: 1, words: 0 } },
{ name: "blank line in the middle counts", input: "a\n\nb\n", expected: { lines: 3, words: 2 } },
{ name: "mixed spaces and tabs", input: " a \t b \n", expected: { lines: 1, words: 2 } },
{ name: "windows line endings", input: "one\r\ntwo\r\n", expected: { lines: 2, words: 2 } },
{ name: "non-ASCII letters", input: "café naïve\n", expected: { lines: 1, words: 2 } },
];
for (const { name, input, expected } of cases) {
test(name, () => {
assert.deepEqual(countText(input), expected);
});
}Typing Case as an interface means a misspelled key such as expcted is a compile error. Because this runs through tsc, the test data gets the same checking as the application code.
Pinning behavior you chose on purpose
Some results are decisions rather than facts. The code splits words on \s+, which in JavaScript includes the non-breaking space \u00a0. The system wc command may treat that character differently depending on locale. If you decide your tool's behavior is "JavaScript whitespace," write a test that says so:
import { test } from "node:test";
import assert from "node:assert/strict";
import { countText } from "./count.js";
test("a non-breaking space separates words", () => {
assert.deepEqual(countText("a\u00a0b"), { lines: 1, words: 2 });
});If someone later changes the splitting rule, this test fails and forces a conscious choice instead of a silent change.
Testing the real command
Unit tests don't cover the wiring: argument handling, the ENOENT message, and the exit codes. A small number of command tests cover that by starting the compiled program as a child process. This is a different kind of test, so keep it in its own file, src/cli.test.ts.
import { test } from "node:test";
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { fileURLToPath } from "node:url";
const run = promisify(execFile);
const cli = fileURLToPath(new URL("./cli.js", import.meta.url));
test("a missing file exits with code 1 and a message on stderr", async () => {
await assert.rejects(
run(process.execPath, [cli, "no-such-file.txt"]),
(err: { code?: number; stderr?: string }) =>
err.code === 1 && /no such file/.test(err.stderr ?? ""),
);
});
test("no arguments exits with code 2 and prints usage", async () => {
await assert.rejects(
run(process.execPath, [cli]),
(err: { code?: number; stderr?: string }) =>
err.code === 2 && /usage: wcl/.test(err.stderr ?? ""),
);
});How this works:
process.execPathis the path of the Node.js binary running the tests. Using it avoids depending on whatnoderesolves to on thePATH.new URL("./cli.js", import.meta.url)locatescli.jsnext to the compiled test file indist, whatever the current working directory is.promisify(execFile)resolves when the child exits with 0 and rejects otherwise. The rejection carries the exit code incodeand the captured output instderr. That is why a failure case usesassert.rejects.- The validation function passed to
assert.rejectsreturnstruewhen the error matches. Afalseresult fails the test.
These tests check that errors go to stderr and that exit codes are 1 and 2, as designed in the error-handling chapter. They would catch a regression such as swapping console.error for console.log.
Common mistakes
- Forgetting to rebuild.
node --test distruns compiled JavaScript. If you call it directly after editing a.tsfile, you test stale code.npm testrunstscfirst, so use that. - Missing
.jsin imports.import { countText } from "./count"fails underNodeNext, both in the compiler and at run time. - Async tests that don't await. If a test calls an async function and doesn't
awaitor return the promise, it can pass before the assertion runs. Make the callbackasyncandawaitevery promise, as the command tests do. - Tests that depend on the working directory.
run(process.execPath, ["dist/cli.js"])works only when you start from the project root. Resolve paths fromimport.meta.url. - Publishing test files. The
filesarray inpackage.jsonincludes all ofdist, which now holds*.test.js. Add"!dist/**/*.test.js"tofilesto keep them out of the published package.
Summary of the testing setup
| Layer | File | Calls | Speed | Checks |
|---|---|---|---|---|
| Unit | `src/count.test.ts` | `countText` directly | milliseconds | line and word rules |
| Command | `src/cli.test.ts` | `node dist/cli.js` | tens of milliseconds | exit codes, stderr, stdout |
Exercise
The input "a\n\n" is passed to countText. What should the result be, and which rule from this chapter does the case test? Write the table row for it.
Show answer
The text splits on "\n" into ["a", "", ""], which has length 3. It ends with "\n", so one is subtracted, giving 2 lines. There is one word. The rule is that a trailing newline ends the last line but does not add a line, while the blank line before it still counts. The row is { name: "blank line before the trailing newline", input: "a\n\n", expected: { lines: 2, words: 1 } }.
Exercise
Your test script is "tsc && node --test dist" and a teammate runs "node --test dist" right after editing src/count.ts. The tests pass, but they should have failed because of the edit. Why, and how do you prevent it?
Show answer
node --test runs the compiled files in dist, and the edit has not been compiled yet, so the old JavaScript is tested. Run the tests through npm test, which runs tsc first, or add a "pretest": "tsc" script. Each of these rebuilds dist before the tests run.
Exercise
Write a command test that checks the success path for a file containing "a b\nc\n". Which Node.js functions create the file and decide where it goes, and what stdout should you assert?
Show answer
Use mkdtemp (with os.tmpdir()) from node:fs/promises to create a temporary directory, and writeFile to write "a b\nc\n" into a file there. Run execFile with process.execPath and the cli path and the file path. It resolves on exit code 0. Assert that stdout equals "2 3 " followed by the file path and a newline, because the program prints ${lines} ${words} ${file}. Remove the directory with rm({ recursive: true }) in a finally block.