Checking your work: your first test with node:test
Write down the right answer once and let a command check it every time: move functions into a file of their own with export, write a test with node:test that calls one with an input whose answer you know, run every test with node --test, and read the + actual / - expected report when one fails. TaskKit’s capitalize and percentFull get their first tests, and Module 5 closes with its one-page cheat sheet.
TypeScript
Fundamentals
Checking your work: your first test with `node:test`. Read this lesson at .
Tested with TypeScript 7.x · Node.js LTS
In lesson 5.10 you found the bug that made your summary print
2 of 3 done (150%): two arguments swapped on one line. You fixed it,
ran the program, and saw 67%. Now picture next week. You tidy
scoreLine and the two numbers trade places again. The program still
runs without a word of complaint. Nobody is watching that line any
more, and the debugger only helps once you have noticed something is
wrong.
A maths textbook has the answers at the back. You work out problem
12, turn to the back, and see at once whether you got it right,
without having to trust your own working. A test is that page
for your code: you write down the right answer for one input once,
and from then on a command checks it for you. By the end of this
lesson, one command, node --test, will check scoreLine and
three of TaskKit's functions every time you run it, and say exactly
which one broke.
A test: a call whose answer you already know
So far you have checked your work by running the program and
reading what it prints. That works while you remember what the
right output looks like and bother to look. 2 of 3 done (150%)
looked like an ordinary line until you did the sum in your head.
A test is a small piece of code that calls one of your functions
with an input you chose, and compares what comes back with the
answer you worked out yourself. What the call gives back is the
actual value; the answer you wrote down is the expected
value. If the two match, the test passes. If they do not, it
fails, and it tells you both. Here is the same bug, met both ways:
2 of 3 done (150%)
Checking by eye
Never: It never says whether 150% is right
What node day.ts prints: you have to notice.
✔ 1 of 4 is 25% (0.390083ms)
✖ 2 of 3 is 67% (0.528125ms)
A test
Does: It compares the answer with the one you wrote down
What node --test prints: a cross on the test that failed.
The same bug, read by you and checked by a test
Underneath, a test is a comparison you could already write. Run
this: it calls scoreLine with the swap still in it and compares
the answer with the right one, using === from lesson 2.3.
compare.tsts
function percentDone(part: number, whole: number): number { return Math.round((part / whole) * 100);}function scoreLine(done: number, all: number): string { const percent = percentDone(all, done); return `${done} of ${all} done (${percent}%)`;}const actual = scoreLine(2, 3);const expected = "2 of 3 done (67%)";console.log(actual === expected);
It prints false. That one line is the heart of every test. What
a testing tool adds is everything around it: it runs many such
comparisons with one command, names each one, keeps them in a file
of their own so they never get in the way of your program, and
shows both values when they differ.
Two files: the functions, and their tests
A test has to call the real function, the one your program runs,
not a copy of it. A copy would pass even after the real one broke.
So the functions move into a file of their own, and the tests go in
a second file that borrows them. Your program can borrow them from
the same place.
score.ts
Holds percentDone and scoreLine, each with export in front,
so another file can use them
score.test.ts
Takes them with import, calls each with an input whose answer
you know, and compares
node --test
Finds every file whose name ends in .test.ts, runs its tests,
and prints a line for each
Who holds what, and who runs it
Two new words do the joining. export in front of a function
means "another file may use this one". import at the top of a
file means "bring that function in from there". A file that holds
only functions and no other lines runs nothing when it is imported:
the functions are declared and wait to be called. Module 9 teaches
these two words properly; this lesson needs only that much.
1
Make score.ts
In ~/projects/taskkit, make a file called score.ts and put the
two functions from lesson 5.10 in it, already fixed, with export
in front of each:
score.tsts
export function percentDone(part: number, whole: number): number { return Math.round((part / whole) * 100);}export function scoreLine(done: number, all: number): string { const percent = percentDone(done, all); return `${done} of ${all} done (${percent}%)`;}
2
Tell Node your files use import
Node expects to be told when a project's files use import. It
learns that from one line in package.json, the list npm (Node
package manager) keeps (lesson 1.4). You do not edit
that list by hand; npm writes the line for you:
bash
npm pkg set type=module
It prints nothing. package.json now holds "type": "module".
Without it, Node still runs your tests but first prints a long
warning, MODULE_TYPELESS_PACKAGE_JSON, about every file that uses
import.
3
Make day.ts borrow them
day.ts still has its own copies, and a test of score.ts would
not watch them. Delete percentDone and scoreLine from day.ts
and put this line at its top instead:
day.tsts
import { scoreLine } from "./score.ts";
Run it, and it prints what it printed before. Do not check it with
npx tsc yet: the section on checking test files below gives
TypeScript the one extra flag an import needs.
bash
node day.ts
Outputtext
2 of 3 done (67%)
Your first test
Make a second file next to score.ts, called score.test.ts. The
.test in the middle of the name is how Node will find it later.
score.test.tsts
import { test } from "node:test";import assert from "node:assert/strict";import { percentDone, scoreLine } from "./score.ts";test("1 of 4 is 25%", () => { assert.equal(percentDone(1, 4), 25);});test("2 of 3 is 67%", () => { assert.equal(scoreLine(2, 3), "2 of 3 done (67%)");});
Read it a line at a time:
Line 1 brings in test from node:test, the testing tool
that comes with Node. The node: in front means it is part of
Node itself; there is nothing to install.
Line 2 brings in assert, Node's tool for comparing values.
There are no braces here: assert is the one thing that file hands
out by default. Braces pick named functions out of a file, as on
lines 1 and 3. /strict picks the version that compares values
exactly, so "25" never counts as equal to 25.
Line 3 brings in your two functions. The path starts with
./, "in this folder", and ends with .ts, the file's whole
name, which Node needs.
Lines 5 to 7 are one test. test takes a name and a function,
the way filter took a rule in lesson 5.4: it is a callback, an
arrow that takes nothing, and test calls it back when the test
runs.
Line 6 is the comparison. assert.equal takes the actual
value first and the expected value second. If they are equal,
nothing happens and the test passes. If not, it stops the test
there and reports both.
The name is the sentence Node prints for the test, so make it say
what is being checked: "2 of 3 is 67%" tells you what broke
without opening the file. Now run every test in the project:
bash
node --test
Outputtext
✔ 1 of 4 is 25% (0.3655ms)✔ 2 of 3 is 67% (0.070417ms)ℹ tests 2ℹ suites 0ℹ pass 2ℹ fail 0ℹ cancelled 0ℹ skipped 0ℹ todo 0ℹ duration_ms 66.257416
If it says tests 0, install the current v24 from nodejs.org, as in
lesson 1.2: v24.0.0 does not yet look for .ts test files.
The --test flag tells Node to look through the folder for test
files, run every test in them, and report. Each test gets a line:
✔ when it passed, its name, and how long it took, which will differ
on your computer. Below them comes a count. pass 2 and fail 0
are the two to read; the other counts are for features you have not
met.
Where does the expected value come from? From you, worked out by
hand, never from the program's own output.
Bad — the expected value copied from
what the swapped version printed, so the test agrees with the bug.
ts
test("2 of 3 is 67%", () => { assert.equal(scoreLine(2, 3), "2 of 3 done (150%)");});
Good — the expected value worked
out from the question itself: two tasks out of three is 67%.
ts
test("2 of 3 is 67%", () => { assert.equal(scoreLine(2, 3), "2 of 3 done (67%)");});
The first test passes with the bug in place and fails the day
someone fixes it, which is exactly backwards. A test copied from
the output only proves the program does what it did yesterday.
When a test fails
Put the swap back into score.ts for a moment, so line 5 reads
percentDone(all, done), and run node --test again. Here is what
happens between Enter and the answer, for the fixed file and for
the one with the swap. Press Next step to walk through it, or
let it play, and switch between the two:
You
node--test
Thetest
score.ts
You: node --test ⏎node--test⏎node--test⏎
node --test: finds the test filefindsthetestfilefindsthetestfile
The test: calls scoreLinecallsscoreLinecallsscoreLine
score.ts: … (67%)…(67%)…(67%)
The test: equal ✔equal✔equal✔
node --test: pass 2, fail 0pass2,fail0pass2,fail0
Time
You type the command in taskkit and press Enter.
Node looks for files whose names end in .test.ts and finds
score.test.ts.
The test calls scoreLine(2, 3): numbers whose answer you
worked out by hand.
scoreLine runs exactly as your program runs it and gives back
"2 of 3 done (67%)".
assert.equal compares the answer with
"2 of 3 done (67%)". They match.
Node prints ✔ before each test's name, then counts them:
pass 2, fail 0.
node --test runs each test; a test calls and compares
All 6 steps shown.Step 1 of 6: You: node --test ⏎Step 2 of 6: node --test: finds the test fileStep 3 of 6: The test: calls scoreLineStep 4 of 6: score.ts: … (67%)Step 5 of 6: The test: equal ✔Step 6 of 6: node --test: pass 2, fail 0
All 6 steps shown.
You
node--test
Thetest
score.ts
You: node --test ⏎node--test⏎node--test⏎
node --test: finds the test filefindsthetestfilefindsthetestfile
The test: calls scoreLinecallsscoreLinecallsscoreLine
score.ts: … (150%)…(150%)…(150%)
The test: not equal ✖notequal✖notequal✖
node --test: pass 1, fail 1pass1,fail1pass1,fail1
Time
You type the command in taskkit and press Enter.
Node looks for files whose names end in .test.ts and finds
score.test.ts.
The test calls scoreLine(2, 3): numbers whose answer you
worked out by hand.
scoreLine hands its numbers over swapped and gives back
"2 of 3 done (150%)".
assert.equal compares the answer with
"2 of 3 done (67%)". They differ, so the test stops here.
Node prints ✖ before this test's name, counts pass 1,
fail 1, and shows what came back and what was expected.
node --test runs each test; a test calls and compares
All 6 steps shown.Step 1 of 6: You: node --test ⏎Step 2 of 6: node --test: finds the test fileStep 3 of 6: The test: calls scoreLineStep 4 of 6: score.ts: … (150%)Step 5 of 6: The test: not equal ✖Step 6 of 6: node --test: pass 1, fail 1
All 6 steps shown.
The test for percentDone(1, 4) still passes: that function is
fine. Only the test that goes through the swapped line fails. Under
the count, Node repeats every failing test with the details. These
are the first lines of it:
Outputtext
✖ failing tests:test at score.test.ts:8:1✖ 2 of 3 is 67% (0.451208ms) AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: actual expected '2 of 3 done (15067%)'
Read it from the top. score.test.ts:8:1 is where the failing test
starts: line 8, the second test. AssertionError is the name
Node gives a comparison that did not hold. In your terminal actual
is green and expected is red, and the line under them merges the two
values (on this page the card has no colours, so the two numbers run
together as 15067): the green 150 is what scoreLine gave back,
the red 67 is what you wrote. Below that come lines starting with
at, a stack trace (lesson 5.8) you can leave alone here, and then a
block that names both values in plain words, the same in every
terminal:
Outputtext
actual: '2 of 3 done (150%)', expected: '2 of 3 done (67%)',
A terminal without colours shows the two values on lines of their
own instead, + for the actual one and - for the expected one.
So the test has done the debugger's first job for you: it says
which function, which input, and what came out instead. Put
percentDone(done, all) back in line 5, run node --test, and
both lines show ✔ again.
Check the test files with TypeScript too
Node runs your tests; TypeScript checks them with tsc (the
TypeScript compiler, which npx starts), as it checks every file. One
thing is new: TypeScript refuses an import path ending in .ts
unless you say you mean it.
bash
npx tsc --noEmit --types node score.test.ts
Outputtext
score.test.ts:3:40 - error TS5097: An import path canonly end with a '.ts' extension when'allowImportingTsExtensions' is enabled.3 import { percentDone, scoreLine } from "./score.ts"; ~~~~~~~~~~~~Found 1 error in score.test.ts:3
The card breaks the message's long first line in two places; in your
terminal it is one line. TS5097 is the number of this message: TS
for TypeScript. The path has to end in .ts for Node, so give
TypeScript the flag the message names. From here on, the check for a
file with an import in it reads:
It prints nothing, which means the file is fine. The command is
long; Module 9 puts all these flags into one settings file so you
can type npx tsc alone.
TaskKit's functions get their tests
Now TaskKit's step, the last of this module: its small functions
get tests. Three of them give back a string or a number, which
makes them easy to test: capitalize and percentFull from lesson
5.1, and alphabetical from lesson 5.4. Like scoreLine, they move
into a file of their own, the first two at once, and alphabetical,
whose test is a little different, once theirs pass. printList,
printBanner and printSummary print instead of giving something
back, and sameTask gives back a function, so assert.equal has
nothing simple to compare for them yet.
1
Move the two functions into tasks.ts
In ~/projects/taskkit, make tasks.ts, and move the declarations
of capitalize and percentFull out of index.ts into it, each
with export in front:
tasks.tsts
export function capitalize(task: string): string { return task.slice(0, 1).toUpperCase() + task.slice(1);}export function percentFull(added: number, limit: number): number { // Rounded: without it, a limit of 3 prints 66.66666666666666 return Math.round((added / limit) * 100);}
2
Import them at the top of index.ts
The rest of index.ts still calls both functions, so bring them
back in. Put this line at the very top of index.ts, above every
function that is left there:
index.tsts
import { capitalize, percentFull } from "./tasks.ts";
3
Write tasks.test.ts
Each test checks one fact, and its name says which. The third is
the case that is easiest to forget: an empty task.
tasks.test.tsts
import { test } from "node:test";import assert from "node:assert/strict";import { capitalize, percentFull } from "./tasks.ts";test("capitalize gives buy milk a capital B", () => { assert.equal(capitalize("buy milk"), "Buy milk");});test("capitalize keeps the rest as typed", () => { assert.equal(capitalize("call Mom"), "Call Mom");});test("capitalize leaves an empty task empty", () => { assert.equal(capitalize(""), "");});test("3 tasks of 5 is 60% full", () => { assert.equal(percentFull(3, 5), 60);});
✔ 1 of 4 is 25% (0.356542ms)✔ 2 of 3 is 67% (0.063833ms)✔ capitalize gives buy milk a capital B (0.378625ms)✔ capitalize keeps the rest as typed (0.061125ms)✔ capitalize leaves an empty task empty (0.053375ms)✔ 3 tasks of 5 is 60% full (0.052166ms)ℹ tests 6ℹ suites 0ℹ pass 6ℹ fail 0ℹ cancelled 0ℹ skipped 0ℹ todo 0ℹ duration_ms 67.358333
node --test found both test files by itself and ran all six
tests. Then run TaskKit as usual, and check that nothing changed:
============================TaskKit 0.1Your tasks, in your terminal============================Added: Pay rentAdded: Call MomAdded: Buy milkTasks added: 3 of 5, room for 2 moreList 60% fullYour list, A to Z:1. Buy milk2. Call Mom3. Pay rent
5
Give alphabetical its test
Now alphabetical. Its answer is a number, below zero when a
comes first, as lesson 4.4 showed for localeCompare. Move it from
index.ts to the end of tasks.ts, with export in front:
tasks.tsts
export function alphabetical(a: string, b: string): number { return a.localeCompare(b);}
Add its name at the end of the import line at the top of
index.ts, and of the same line at the top of tasks.test.ts:
index.tsts
import { capitalize, percentFull, alphabetical } from "./tasks.ts";
tasks.test.tsts
import { capitalize, percentFull, alphabetical } from "./tasks.ts";
localeCompare promises only a number below zero, not which number,
so you cannot write the expected value by hand. Test what you care
about instead: the order it gives a list. Add a test at the end of
tasks.test.ts whose actual value is the first task of a list
sorted with alphabetical:
✔ 1 of 4 is 25% (0.7615ms)✔ 2 of 3 is 67% (0.084375ms)✔ capitalize gives buy milk a capital B (0.798458ms)✔ capitalize keeps the rest as typed (0.089125ms)✔ capitalize leaves an empty task empty (0.059125ms)✔ 3 tasks of 5 is 60% full (0.059583ms)✔ alphabetical puts buy milk first (7.82375ms)ℹ tests 7ℹ suites 0ℹ pass 7ℹ fail 0ℹ cancelled 0ℹ skipped 0ℹ todo 0ℹ duration_ms 107.13975
Run TaskKit as you did above once more: TaskKit prints exactly what it
printed before. The tests and the program now call the very same
capitalize, percentFull and alphabetical, so when you change one
of them, node --test tells you in a second whether it still gives
the right answers.
Predict before you run
Someone "improves" capitalize, so every task is tidied the same
way. Read the new version against the five tests in
tasks.test.ts and decide what node --test will count.
Predict
How many tests does node --test count as fail?
tasks.tsts
export function capitalize(task: string): string { return task.slice(0, 1).toUpperCase() + task.slice(1).toLowerCase();}export function percentFull(added: number, limit: number): number { // Rounded: without it, a limit of 3 prints 66.66666666666666 return Math.round((added / limit) * 100);}export function alphabetical(a: string, b: string): number { return a.localeCompare(b);}
The common mistake: a function without export
When you move a function into a file of its own, the line you
copied is function capitalize(…), and export is the word you
have to add. It is easy to add it to the first function and miss
the second.
Common mistake
Importing a function its file does not export
score.ts has export in front of percentDone, but not in
front of scoreLine:
node --test stops before a single test of that file runs. The
import on line 3 of score.test.ts asks for something score.ts
does not share.
SyntaxError: The requested module './score.ts' does not provide an export named 'scoreLine'
The fix
Put export in front of every function another file uses:
score.tsts
export function scoreLine(done: number, all: number): string {
The message names the file and the missing name, so read it as "go
to score.ts, find scoreLine, add export". TypeScript catches
it too, before you run anything: the check prints TS2459, which
says scoreLine is declared in that file "but it is not exported".
Pass all four tasks to complete the lesson with practice. Reach the end without them and it counts as read only.
Exercises
These run on this page, where there are no other files to import from,
so you run the test files themselves in your terminal. Here you read
reports, write expected values, and fix or write functions until the
checks, written like the tests, all pass.
Exercise · Read the code
Read the failure
node --test prints this for one of TaskKit's tests. What did
percentFull give back?
text
✖ 3 tasks of 5 is 60% full (0.48ms) AssertionError [ERR_ASSERTION]: Expected values to be strictly equal: 167 !== 60
Exercise · Predict the result
Write the expected value
You add a third test to score.test.ts. Work out by hand what
should go in place of ???, written exactly as the code needs it.
This capitalize fails two of TaskKit's three capitalize tests.
Fix the function so all three pass.
Loading the editor…
Exercise · Write the code
Finish a function from its tests
TaskKit's summary will need a word that agrees with its number.
These tests are already written (not in your file), and the
function only half works:
ts
test("3 is 3 tasks", () => { assert.equal(taskWord(3), "3 tasks");});test("1 is 1 task", () => { assert.equal(taskWord(1), "1 task");});test("0 is 0 tasks", () => { assert.equal(taskWord(0), "0 tasks");});
Finish taskWord so all three pass.
Loading the editor…
Recap
Recap · 3 questions
Check yourself
What does a test do?
Check yourself
actual: 150%, expected: 67%; 67% is right. What do you fix?
Check yourself
Why does score.ts need export in front of scoreLine?
0 of 0 answered.
A cheat sheet to keep
Cheat sheet
Checking your work: your first test with node:test
What things are
Word
What it means
Test
A call with a known input, compared with its answer
Actual value
What the function gave back
Expected value
The answer you worked out by hand
Test file
A file whose name ends in .test.ts
node:test
The testing tool that comes with Node
assert.equal
Compares actual with expected; stops the test if not
AssertionError
Node's name for a comparison that did not hold
export
Lets another file use this function
import
Brings a function in from another file
Code and commands
Write
To
npm pkg set type=module
Tell Node the project uses import, once
export function …
Share a function with other files
from "./score.ts"
Import from this folder; the .ts is needed
import { test }
From "node:test": the test function
import assert
From "node:assert/strict": comparisons
test("…", () => { … })
One test: a name and a callback
assert.equal(actual, expected)
Actual first, expected second
node --test
Find every test file, run it, report
Rules
Rule
What it means
Expected by hand
Never copy it from what the program printed
actual: and expected:
What came back, and what you wrote
Fix the function
When the expected value is right
One fact per test
And a name that says which
No export
does not provide an export named …; TS2459
Check with the flag
--allowImportingTsExtensions, or TS5097
Module 5 on one page
Cheat sheet
Module 5: Functions
5.1 Declaring functions: parameter and return types
Write
To
function left(…) { … }
Declare a function called left
(used: number)
Take one parameter; its type always written
): number {
Promise what comes out
return 60 - used;
Hand a value back and end the call
5.2 Arrow functions
Write
To
(task) => task.trim()
A rule for a method, which gives task its type
const left = (…) => …
Keep an arrow in a box; call it left(25)
=> { …; return x; }
A body in braces, giving back x
5.3 Optional, default, and rest parameters
Write
To
minutes?: number
Let a call leave it out; number | undefined
minutes = 15
Use 15 when it is left out
...minutes: number[]
Take any number of numbers, as one list
5.4 Functions as values: callbacks and function types
Write
To
today.filter(isCall)
Hand a method your own function
rule: (task: string) => boolean
Take a function as a parameter
Parentheses run it
Without them, the function is handed over
5.5 Scope and closures (basics)
Rule
What it means
Inside sees out
A function reads the boxes around it
Outside sees nothing in
A box in braces ends at their }
Closure
A function with the outside boxes it uses
5.6 void: functions that return nothing
Write
To
): void {
Promise to give nothing back
today.forEach(printTask)
Run an action for every task
Answer or do
Return what a caller needs; print the rest
5.7 Breaking a problem into small functions
Rule
What it means
Plain-language steps
What the program does, in words, before any code
One job
A step whose name needs "and" is two steps
Main function
Runs the plan, step by step
5.8 The call stack
Word
What it means
Call stack
Every call under way, the newest on top
Frame
One call's card: its boxes and the line it waits on
Stack trace
The pile when Node stopped, top frame first
5.9 Recursion: a function that calls itself
Word
What it means
Base case
The call it answers alone
Recursive case
One step, then a call with a smaller job
RangeError
Maximum call stack size exceeded: no stop
5.10 The debugger: stepping through a function
Press
To
F9
Set or remove a breakpoint on this line
Step Over, F10
Run the yellow line whole
Step Into, F11
Pause on the first line of the call
Debug terminal
No Debugger attached., no pause
5.11 Checking your work: your first test
Write
To
export function …
Share a function with other files
test("…", () => { … })
One test: a name and a callback
assert.equal(actual, expected)
Actual first, expected second
node --test
Find every test file, run it, report
Where to go next
You can now write a test that calls a function with an input whose
answer you know, run every test in the project with one command,
and read a failure: which test, what came back, and what was
expected. TaskKit's functions are small, and the three that give
back a string or a number are tested. That closes Module 5.
Next is Objects and object types, the first lesson of Module 6.
So far a task has been one string. There a task becomes a single
value that holds several facts at once, its title, its minutes,
whether it is done, and TypeScript checks every one of them.
Before you move on, break alphabetical on purpose: in
tasks.ts, make it return b.localeCompare(a);. Predict which test
fails and what the report says came back, then run node --test.
Put a and b back and run it once more.