Skip to content
HopperHopper

Course navigation

Phase 4 · The browserDay 22

Testing with Vitest

  • About 70 minutes
  • 8 sections
  • Runnable TypeScript examples
  • Practice questions

Before you start

About 70 minutes

By the end you will be able to

  1. Explain which bugs the type checker cannot catch, and catch them with tests that run with one command.
  2. Write tests with describe, it and expect, and choose between toBe, toEqual and toThrow.
  3. Move logic out of event handlers into pure functions, and test them with normal input, edge cases and bad input.
  4. Test DOM code in the jsdom environment, and read a failing test's output to find the bug.

What to remember from earlier

Section 1 of 8

22.1 Why Test

Before you start, set up a new project folder named day22 the way you set up a Node project on Day 13: open the folder in VS Code, run npm init -y, set "type": "module" in package.json, run npm install --save-dev typescript @types/node, and add the same tsconfig.json. Each example today is a small project of its own, so give each one its own subfolder (first-test, grades, and so on) inside day22, and run the commands from the folder that holds package.json.

For three weeks the type checker has been your safety net. Type average("90") where a number belongs, and npx tsc stops you before the program ever runs. That net is strong, but it has holes, and today is about the bugs that fall through them.

Here is the average function from your Day 12 grade book, with a mistake in it. Read it once and see whether you can spot the mistake before you look at the output.

Worked example: A bug the type checker cannot see

average-bug.ts
function average(scores: number[]): number {
  let total = 0;
  for (let i = 1; i < scores.length; i++) {
    total += scores[i];
  }
  return total / scores.length;
}

console.log(average([90, 80, 70]));
console.log(average([]));
50
NaN

npx tsc reports nothing for this file: every value has the right type. scores is a number[], total is a number, scores[i] is a number, and the function returns a number. And yet both answers are wrong:

  • The average of 90, 80 and 70 is 80, not 50. The loop on line 3 starts at i = 1, so it skips scores[0]. It adds only 80 and 70, getting 150, then divides by 3.
  • The average of no scores at all is printed as NaN (“not a number”), because line 6 works out 0 / 0. NaN is a number as far as the checker is concerned, so nothing complains.

Compare that with a mistake the checker does catch. This version has the loop right, but the call passes strings:

average-wrong-type.ts
function average(scores: number[]): number {
  let total = 0;
  for (const score of scores) {
    total += score;
  }
  return total / scores.length;
}

console.log(average(["90", "80"]));
average-wrong-type.ts:9:22 - error TS2322: Type 'string' is not assignable to type 'number'.

The type checker answers one question: does every value have the type the code says it should? It never asks is this the right answer? It cannot know that you meant to start the loop at 0, or that an average of 90, 80 and 70 should be 80. Only you know what the right answer is. A bug is a place where a program does something other than what its author meant, and many bugs have perfectly correct types.

You have been finding those bugs by running a program and reading what console.log printed. That works once, but it does not last. Every time you change the code, you would have to run it again and recheck every printed line by eye, and you would soon stop doing it. A test is a small piece of code that calls your code with an input you chose and checks that the result is the answer you expected. An automated test does that check itself and reports pass or fail, so you can rerun hundreds of checks with one command after every change.

Question Who answers it When
Is a string being passed where a number belongs? The type checker npx tsc, before the program runs
Can this value be undefined here? The type checker npx tsc, before the program runs
Is the average of 90, 80 and 70 really 80? A test npm test, by running the code
Does an empty list give an error instead of NaN? A test npm test, by running the code

Key idea

The type checker proves your values have the right types; a test checks that your code gives the right answers. You need both.

Pause and try

Question 1 · Multiple choice

Which of these mistakes would npx tsc report, without any tests?

  1. A letterGrade function that returns "B" for a score of 90 when it should return "A".
  2. A loop that adds up prices but forgets the last one.
  3. A call letterGrade("90") to a function whose parameter is score: number.
  4. A function that divides by scores.length when the list is empty.
Check your reasoning

C. Passing a string where a number parameter belongs is a type mistake, and the type checker reports it (TS2345, an argument of the wrong type).

  • A is wrong because "B" and "A" are both strings; the type is right, only the answer is wrong. Only a test that expects "A" for 90 would catch it.
  • B is wrong because a sum missing one price is still a number.
  • D is wrong because 0 / 0 is NaN, which has type number. The checker has no idea that you did not want NaN.

Reread 22.1 Why Test if you chose differently.

Question 2 · Short answer

A classmate says: “My program type-checks with no errors, so it has no bugs.” In two or three sentences, explain what is wrong with that claim, using average-bug.ts as your example.

Check your reasoning

The type checker only checks that each value has the type the code declares; it does not check that the values are the right answers. average-bug.ts type-checks cleanly, yet it prints 50 instead of 80 because its loop skips the first score, and NaN for an empty list. Bugs like these, wrong answers with correct types, are what tests are for.

A good answer says: the checker checks types, not answers; a program can have correct types and still be wrong; tests catch wrong answers.

Reread 22.1 Why Test if your answer was different.

Section 2 of 8

22.2 Installing Vitest

A test needs something to run it: something that finds your tests, calls each one, notices which ones failed, and prints a report. That is a test runner. Vitest is a test runner for JavaScript and TypeScript. It is made by the same team as Vite, the tool that has been serving your web pages since Day 18, and it runs .ts files directly.

Vitest is a tool you need while you build your program, not something the finished program uses, so it is a dev dependency, the same as typescript was on Day 13. In the terminal, in your day22 folder:

npm install --save-dev vitest

npm downloads Vitest into node_modules and adds it to devDependencies in package.json. Next, give the project a test script, so that one short command runs every test. Open package.json and add a line to "scripts":

"scripts": {
  "check": "tsc",
  "test": "vitest run"
}

Each part of that line matters:

Piece What it does
"test" The script’s name. npm test is a built-in shortcut for npm run test; both work.
vitest Starts Vitest from node_modules.
run Runs every test once, prints the report, and stops. Without it, Vitest stays running in watch mode.

Watch mode means Vitest keeps running and reruns the tests every time you save a file. That is handy while you work, so you can try it with npx vitest: the terminal stays busy, and you press q to quit. The test script uses run so that npm test always finishes with an answer.

Where do the tests go? Vitest looks through your project for files whose names end in .spec.ts or .test.ts and runs those. It ignores every other file. In this course, a test file sits next to the file it tests and shares its name: the tests for grades.ts live in grades.spec.ts. (Spec is short for specification: the file spells out how the code is supposed to behave.)

There is one more thing to know before you write a test. Vitest strips the types off your .ts files and runs the JavaScript that is left, the same way node does. It does not run the type checker. A test file with a type error can still pass. So npm test checks answers, npm run check checks types, and you run both before you call your work done.

Watch out

If you write the script as "test": "vitest", nothing is broken, but npm test never ends: Vitest starts in watch mode and waits for you to save a file. If your terminal seems stuck after the report, that is why. Press q, and add run to the script.

Pause and try

Question 3 · Multiple choice

A project has these four files. Which one does npm test run as tests?

  1. grades.ts
  2. grades.spec.ts
  3. gradesSpec.ts
  4. main.ts
Check your reasoning

B. Vitest runs files whose names end in .spec.ts (or .test.ts).

  • A is wrong because grades.ts is the code under test. Vitest loads it only when a test file imports it.
  • C is wrong because the name must end in .spec.ts, with the dot. gradesSpec.ts ends in plain .ts.
  • D is wrong because main.ts is the program you run with node, not a test file.

Reread 22.2 Installing Vitest if you chose differently.

Question 4 · Short answer

Your tests all pass with npm test. Why should you still run npm run check before you call the work finished?

Check your reasoning

Vitest removes the types and runs the code without asking the type checker anything, so a file with a type error can still pass its tests. npm run check runs tsc, which is the only one of the two commands that finds type errors.

A good answer says: Vitest does not type-check; tsc does; you need both.

Reread 22.2 Installing Vitest if your answer was different.

Section 3 of 8

22.3 describe, it and expect

Now write a first test. Start with the correct average (the loop begins at the first score). It goes in grades.ts and is exported, so that other files can import it, as on Day 13:

first-test/grades.ts
export function average(scores: number[]): number {
  let total = 0;
  for (const score of scores) {
    total += score;
  }
  return total / scores.length;
}

A test needs three things: a name that says what should happen, some code that runs your function, and a check of the result. Vitest gives you a function for each, and you import them from the "vitest" package at the top of the test file:

Function What it does
describe Groups related tests under one name, usually the name of the function they test. Optional, but it keeps the report tidy.
it Defines one test case: a name that reads like a sentence (“it adds the scores…”) and a function holding the test’s code.
expect Wraps the value you got, so you can check it. expect(actual).toBe(expected) is one assertion: a claim that must be true for the test to pass.

Here is the test file:

Worked example: A first test file

first-test/grades.spec.ts
import { describe, expect, it } from "vitest";
import { average } from "./grades.ts";

describe("average", () => {
  it("adds the scores and divides by how many there are", () => {
    expect(average([90, 80, 70])).toBe(80);
  });

  it("returns the score itself for a single score", () => {
    expect(average([88])).toBe(88);
  });
});

Read it line by line:

  • Line 1 imports Vitest’s three functions. Line 2 imports average from grades.ts, the same way main.ts would.
  • Line 4 calls describe with two arguments: the group’s name, "average", and an arrow function. Notice that you do not call that arrow function yourself. You hand it to describe, and describe calls it, exactly like the callbacks you passed to other functions on Day 10.
  • Line 5 calls it the same way: a name and a function. Vitest saves the function and calls it when it runs the tests.
  • Line 6 is the test’s body. average([90, 80, 70]) runs your code. expect(...) wraps the result, which is 80. .toBe(80) checks that it is 80. If it is, the test passes; if not, the test fails and Vitest reports both values.
  • Lines 9 to 11 are a second test case with a different input: one score.

Now run it:

npm test

Vitest prints a line naming its version and folder, then a summary like this, then the time it took:

 Test Files  1 passed (1)
      Tests  2 passed (2)

Test Files counts the .spec.ts files it ran; Tests counts the it calls inside them. Both tests passed.

To see each test by name, ask Vitest for its verbose report:

npx vitest run --reporter=verbose
 ✓ grades.spec.ts > average > adds the scores and divides by how many there are 1ms
 ✓ grades.spec.ts > average > returns the score itself for a single score 0ms

Each test’s full name is its file, its describe group and its it name joined with >. That is why the names are written as sentences: read together, average > adds the scores and divides by how many there are says exactly what the code promises. The times at the end of each line will be different on your computer.

Why is this better than a main.ts that prints average([90, 80, 70])? The program prints 80, and you have to remember that 80 is right. The test already knows that 80 is right; it says so on line 6. Nobody has to read anything unless a test fails. And the test still exists next month, when you change average and have forgotten what it should print.

Watch out

describe, it and expect are not built into JavaScript. They are ordinary functions exported by Vitest, so a test file must import them. Here is a test file that forgot line 1:

function double(n: number): number {
  return n * 2;
}

describe("double", () => {
  it("doubles a number", () => {
    expect(double(4)).toBe(8);
  });
});

npm test reports the whole file as failed, before any test runs:

 FAIL  double.spec.ts [ double.spec.ts ]
ReferenceError: describe is not defined

This is a runtime error, not a type error: the code ran and reached a name that does not exist. The fix is the import: import { describe, expect, it } from "vitest"; as the first line.

Pause and try

Question 5 · Tracing

A test file grades.spec.ts contains describe("letterGrade", () => { ... }), and inside it, it("gives a B for 89", () => { ... }). That test passes. Write the line the verbose report prints for it (leave out the time).

Check your reasoning
 ✓ grades.spec.ts > letterGrade > gives a B for 89

The full name joins the file name, the describe name and the it name with >, in that order. The ✓ marks a passing test.

Reread 22.3 describe, it and expect if your answer was different.

Question 6 · Multiple choice

A test body contains only the line expect(average([90, 80, 70])); with no .toBe(...) after it. What happens when you run it?

  1. The test fails, because there is no expected value.
  2. The test passes, because nothing was checked.
  3. npm test stops with a ReferenceError.
  4. The test prints 80 and then passes.
Check your reasoning

B. expect(...) only wraps the value; the check happens in the matcher (.toBe(80)). With no matcher, no claim is made, nothing can fail, and Vitest counts the test as passed. That makes it a useless test, which is worse than none, because it looks like protection.

  • A is wrong because Vitest does not complain about a missing check; the test simply checks nothing.
  • C is wrong because expect was imported and the code runs normally.
  • D is wrong because expect never prints the value; only a failure report shows values.

Reread 22.3 describe, it and expect if you chose differently.

Section 4 of 8

22.4 Matchers: toBe, toEqual and toThrow

The part after expect(...), such as .toBe(80), is called a matcher: a method that compares the actual value with what you expected and fails the test if they do not match. Vitest has dozens, but three cover almost everything you will write this week. To see all three, here is a fuller grades.ts. average now throws an error for an empty list instead of quietly returning NaN (the throw you learned in 16.1), and two grade functions are added:

grades/grades.ts
export type Letter = "A" | "B" | "C" | "D" | "F";

export function average(scores: number[]): number {
  if (scores.length === 0) {
    throw new Error("Cannot average an empty list of scores");
  }
  let total = 0;
  for (const score of scores) {
    total += score;
  }
  return total / scores.length;
}

export function letterGrade(score: number): Letter {
  if (score >= 90) return "A";
  if (score >= 80) return "B";
  if (score >= 70) return "C";
  if (score >= 60) return "D";
  return "F";
}

export function letterGrades(scores: number[]): Letter[] {
  return scores.map(letterGrade);
}
grades/main.ts
import { average, letterGrade, letterGrades } from "./grades.ts";

const scores = [95, 72, 40];
console.log(average(scores));
console.log(letterGrade(average(scores)));
console.log(letterGrades(scores));
69
D
[ 'A', 'C', 'F' ]

The average of 95, 72 and 40 is 207 ÷ 3 = 69, a D. letterGrades uses map to turn each score into a letter, giving a new array.

Worked example: One matcher of each kind

grades/grades.spec.ts
import { describe, expect, it } from "vitest";
import { average, letterGrade, letterGrades } from "./grades.ts";

describe("average", () => {
  it("adds the scores and divides by how many there are", () => {
    expect(average([90, 80, 70])).toBe(80);
  });

  it("throws for an empty list", () => {
    expect(() => average([])).toThrow("empty list");
  });
});

describe("letterGrade", () => {
  it("gives an A for exactly 90", () => {
    expect(letterGrade(90)).toBe("A");
  });

  it("gives a B for 89", () => {
    expect(letterGrade(89)).toBe("B");
  });
});

describe("letterGrades", () => {
  it("turns each score into a letter, in order", () => {
    expect(letterGrades([95, 72, 40])).toEqual(["A", "C", "F"]);
  });
});

All five tests pass. Each matcher is doing a different job:

  • toBe (lines 6, 16 and 20) checks that the actual value is the same value as the expected one, in the same way as ===. It is the right matcher for numbers, strings and booleans: 80 is 80, and "A" is "A".
  • toEqual (line 26) checks that two values have the same contents. letterGrades returns a brand-new array, and line 26 writes another brand-new array. As you saw in 6.5, === between two different arrays is false even when their elements match, so toBe would fail here. toEqual instead compares element by element (and for objects, property by property), which is what you want for arrays and objects.
  • toThrow (line 10) checks that a function throws an error. Look closely: expect gets an arrow function, () => average([]), not the result of calling average. Vitest calls that function inside a try, catches the error, and checks it. The string "empty list" is optional; when you give one, the error’s message must contain it. The real message is "Cannot average an empty list of scores", which contains "empty list", so the test passes.
Matcher Passes when Use it for
toBe(x) The actual value === x Numbers, strings, booleans
toEqual(x) The actual value has the same contents as x Arrays and objects
toThrow("text") Calling the function throws an error whose message has text Code that should reject bad input

Watch out

Using toBe on an array. This assertion looks right, but fails:

expect(letterGrades([95, 72])).toBe(["A", "C"]);
AssertionError: expected [ 'A', 'C' ] to be [ 'A', 'C' ] // Object.is equality

If it should pass with deep equality, replace "toBe" with "toStrictEqual"

Expected: [ 'A', 'C' ]
Received: serializes to the same string

The two arrays look identical, and Vitest even says so (“serializes to the same string”), but they are two different arrays, so toBe fails, just as === would. Object.is equality in the message is the comparison toBe uses; for everyday values it behaves like ===. Vitest suggests toStrictEqual, a stricter cousin of toEqual; for arrays like this one, toEqual is all you need.

Watch out

Calling the function inside expect for toThrow. This test is meant to check the error:

expect(average([])).toThrow("empty list");

But average([]) runs first, as the argument to expect, and throws before expect or toThrow can do anything. The error escapes the test, and Vitest reports the test as failed with the error itself:

Error: Cannot average an empty list of scores
 ❯ average grades.ts:5:11

The fix is to hand expect a function that makes the call, so toThrow can call it and catch the error: expect(() => average([])).toThrow("empty list");.

Pause and try

Question 7 · Multiple choice

orderSizes() returns a new array ["S", "M", "L"]. Which assertion is right for it?

  1. expect(orderSizes()).toBe(["S", "M", "L"]);
  2. expect(orderSizes()).toEqual(["S", "M", "L"]);
  3. expect(() => orderSizes()).toEqual(["S", "M", "L"]);
  4. expect(orderSizes()).toThrow(["S", "M", "L"]);
Check your reasoning

B. An array is compared by its contents with toEqual.

  • A fails because toBe asks whether the two arrays are the same array, and the array written in the test is a different one.
  • C is wrong because the arrow function is only needed for toThrow. Here expect would hold a function, and a function is not equal to an array.
  • D is wrong because toThrow is for errors; orderSizes does not throw.

Reread 22.4 Matchers: toBe, toEqual and toThrow if you chose differently.

Question 8 · Debugging

This test is meant to check that letterGrade never accepts a negative score, using a version of letterGrade that throws new Error("Score cannot be negative"). Instead of passing, the test fails with Error: Score cannot be negative. Find the mistake and fix the line.

expect(letterGrade(-5)).toThrow("negative");
Check your reasoning

letterGrade(-5) is called as the argument to expect, so it throws before toThrow can catch anything; the error escapes the test, and Vitest shows it. Give expect a function that makes the call instead:

expect(() => letterGrade(-5)).toThrow("negative");

Now toThrow calls the arrow function itself, catches the error, and checks that its message contains "negative".

Reread the second Watch Out in 22.4 Matchers: toBe, toEqual and toThrow if you missed it.

Section 5 of 8

22.5 Testing Pure Functions

On Day 19 you built a counter with increment, decrement and reset buttons. A first version often puts all the logic straight into the click handlers, something like this:

plusButton.addEventListener("click", () => {
  if (count < 10) {
    count += 1;
  }
  output.textContent = String(count);
});

How would you test that the count stops at 10? The rule “stop at 10” is buried inside a function that only runs when someone clicks a real button on a real page, and its result goes straight into an element. To test it you would need a page, a button, a click and an element to read back, all to check one if.

Recall the pure function from 8.8: its result depends only on its arguments, and it changes nothing outside itself. No page, no localStorage, no console.log. A pure function is the easiest thing in the world to test: call it with some arguments and check what it returns. So the design rule for testable code is: keep the logic in pure functions, and keep event handlers thin. A handler should only gather what happened (which button, what was typed), pass it to a pure function, store the result and call render().

Worked example: The counter's logic, moved out and tested

All the counter’s rules move into one pure function in its own module:

counter/counter.ts
export type CounterAction = "increment" | "decrement" | "reset";

/** The count after one button press. The count stays between 0 and max. */
export function nextCount(count: number, action: CounterAction, max = 10): number {
  if (action === "reset") return 0;
  if (action === "increment") return Math.min(count + 1, max);
  return Math.max(count - 1, 0);
}

nextCount takes the current count and which button was pressed (a literal union, so the checker rejects any other action), and returns the new count. Line 6 uses Math.min so the count never passes max; line 7 uses Math.max so it never drops below 0. The max = 10 default lets a caller choose another limit. It touches no element at all, so it can be tested with plain values:

counter/counter.spec.ts
import { describe, expect, it } from "vitest";
import { nextCount } from "./counter.ts";

describe("nextCount", () => {
  it("adds one on increment", () => {
    expect(nextCount(3, "increment")).toBe(4);
  });

  it("subtracts one on decrement", () => {
    expect(nextCount(3, "decrement")).toBe(2);
  });

  it("goes back to 0 on reset", () => {
    expect(nextCount(7, "reset")).toBe(0);
  });

  it("never goes below 0", () => {
    expect(nextCount(0, "decrement")).toBe(0);
  });

  it("never goes above the maximum", () => {
    expect(nextCount(10, "increment")).toBe(10);
    expect(nextCount(5, "increment", 5)).toBe(5);
  });
});

All five tests pass. The last test has two assertions; a test passes only if every assertion in it passes. The handlers on the page shrink to one line of logic each:

plusButton.addEventListener("click", () => {
  count = nextCount(count, "increment");
  render();
});

The handler no longer decides anything. Every decision is in nextCount, and every decision is tested.

Pure functions also run in plain Node, which gives a quick check that they work together. This main.ts presses increment twice and decrement once:

counter/main.ts
import { nextCount } from "./counter.ts";

let count = 0;
count = nextCount(count, "increment");
count = nextCount(count, "increment");
count = nextCount(count, "decrement");
console.log(count);
1

Starting from 0: increment gives 1, increment gives 2, decrement gives 1.

Key idea

Put decisions in pure functions that take values and return values. Event handlers only collect input, call those functions, store the result and render. Then the decisions can be tested without a page.

Pause and try

Question 9 · Short answer

A handler for a “Add to cart” button reads the quantity box, adds the quantity to a running total, caps the total at 99, and writes it into a <span>. Which part should become a pure function, and what would its parameters and return value be?

Check your reasoning

The decision, “add the quantity to the total but never go above 99”, becomes a pure function such as addToTotal(total: number, quantity: number): number, which returns the new total. The handler keeps only the page work: reading the input, calling addToTotal, storing the result, and writing it into the <span>.

A good answer says: the calculation and the cap move out; the function takes plain values and returns the new total; reading inputs and changing the page stay in the handler.

Reread 22.5 Testing Pure Functions if your answer was different.

Question 10 · Multiple choice

Which function is easiest to test with expect(...).toBe(...)?

  1. function showTotal(total: number): void that sets an element’s textContent.
  2. function saveTotal(total: number): void that writes to localStorage.
  3. function addTax(price: number): number that returns the price with tax added.
  4. function logTotal(total: number): void that calls console.log.
Check your reasoning

C. addTax is pure: it takes a number and returns a number, so a test calls it and checks the result with toBe.

  • A is wrong because it returns nothing (void); its effect is on the page, so a test would need a page to look at.
  • B is wrong because its effect is in localStorage, outside the function.
  • D is wrong because its only effect is printing; there is no return value to check.

Reread 22.5 Testing Pure Functions if you chose differently.

Section 6 of 8

22.6 Edge Cases and Bad Input

A test of average([90, 80, 70]) checks the case you had in mind when you wrote average. Bugs rarely live there. They live at the edges: the empty list, the very first item, the exact cut-off score. An edge case is an input at the limit of what the code is meant to handle. A boundary is a value where the answer changes, like 90 for an A, and the values on each side of it are where > versus >= mistakes show up.

On Day 20 you learned that form values are always strings, so a shop’s quantity box hands you text, and you must turn it into a number. JavaScript’s Number has some surprises waiting:

number-empty.ts
console.log(Number("12"));
console.log(Number(""));
console.log(Number("   "));
console.log(Number("2.5"));
console.log(Number("two"));
12
0
0
2.5
NaN

An empty box and a box of spaces both become 0, not NaN. A decimal goes straight through. Code that only checks for NaN would accept all three. Those are exactly the inputs a test should try.

Before you write the tests for a function that reads input, go through this list and ask which ones apply:

Kind of input For a quantity box from 1 to 99
A normal value "3"
Each end of the allowed range "1" and "99"
Just outside each end "0" and "100"
Empty or only spaces "" and " "
Spaces around a good value " 3 "
The wrong kind of value "two" and "2.5"

Worked example: Testing parseQuantity

parseQuantity turns the text from a quantity box into a whole number from 1 to 99, or throws a clear error:

quantity/quantity.ts
/** Turns the text from a quantity box into a whole number from 1 to 99. */
export function parseQuantity(text: string): number {
  const trimmed = text.trim();
  if (trimmed === "") {
    throw new Error("Enter a quantity");
  }
  const quantity = Number(trimmed);
  if (!Number.isInteger(quantity)) {
    throw new Error(`"${trimmed}" is not a whole number`);
  }
  if (quantity < 1 || quantity > 99) {
    throw new Error("Quantity must be from 1 to 99");
  }
  return quantity;
}

Line 3 trims the spaces. Line 4 catches the empty box before Number can turn it into 0. Line 8 uses Number.isInteger, which is true only for a whole number, so it rejects both 2.5 and NaN in one check. Line 11 checks the range. Each row of the table above becomes an assertion:

quantity/quantity.spec.ts
import { describe, expect, it } from "vitest";
import { parseQuantity } from "./quantity.ts";

describe("parseQuantity", () => {
  it("reads a normal quantity", () => {
    expect(parseQuantity("3")).toBe(3);
  });

  it("ignores spaces around the number", () => {
    expect(parseQuantity(" 3 ")).toBe(3);
  });

  it("accepts both ends of the range", () => {
    expect(parseQuantity("1")).toBe(1);
    expect(parseQuantity("99")).toBe(99);
  });

  it("rejects numbers just outside the range", () => {
    expect(() => parseQuantity("0")).toThrow("from 1 to 99");
    expect(() => parseQuantity("100")).toThrow("from 1 to 99");
  });

  it("rejects an empty box", () => {
    expect(() => parseQuantity("")).toThrow("Enter a quantity");
    expect(() => parseQuantity("   ")).toThrow("Enter a quantity");
  });

  it("rejects text and decimals", () => {
    expect(() => parseQuantity("two")).toThrow("not a whole number");
    expect(() => parseQuantity("2.5")).toThrow("not a whole number");
  });
});

All six tests pass. Two tests check the happy path (the normal and spaced values); four check edges and bad input. Bad input is tested with toThrow, and each one names part of the message it expects, so a test also fails if the wrong error is thrown, for example if "" reported “Quantity must be from 1 to 99” instead of “Enter a quantity”.

The function works the same from a program:

quantity/main.ts
import { parseQuantity } from "./quantity.ts";

console.log(parseQuantity(" 12 "));
try {
  parseQuantity("");
} catch (error) {
  if (error instanceof Error) {
    console.log(error.message);
  }
}
12
Enter a quantity

Watch out

Testing only the happy path. A test file with only expect(parseQuantity("3")).toBe(3) passes for the version above, but it would also pass for a version with no empty check, no whole-number check and no range check at all, because Number("3") is 3. A test that cannot fail for a broken version proves nothing about it. For every if in your function, write at least one test that goes down that branch.

Pause and try

Question 11 · Tracing

Someone changes line 11 of quantity.ts to if (quantity < 1 || quantity >= 99) {. Which of the six tests in quantity.spec.ts fails, and why?

Check your reasoning

Only “accepts both ends of the range” fails. With >= 99, parseQuantity("99") throws “Quantity must be from 1 to 99” instead of returning 99, and an error inside a test fails it. Every other test still passes: "100" is still rejected (100 ≥ 99), "1" is still accepted, and the other inputs never reach line 11 or are unaffected.

This is why the table tests both ends of the range: a test of "50" alone would never notice.

Reread 22.6 Edge Cases and Bad Input if your answer was different.

Question 12 · Short answer

A function parsePercent(text: string): number should accept whole numbers from 0 to 100 and throw for anything else. List six inputs you would test, and say what each one should do.

Check your reasoning

A good set (others are fine if they cover the same kinds):

  • "50" returns 50 (a normal value).
  • "0" returns 0 and "100" returns 100 (both ends of the range).
  • "-1" throws and "101" throws (just outside each end).
  • "" throws (empty box, which Number would turn into 0).
  • "12.5" throws (not a whole number).
  • "fifty" throws (not a number at all).

A good answer covers a normal value, both ends, just outside both ends, the empty string, and a wrong kind of value.

Reread the table in 22.6 Edge Cases and Bad Input if you missed a kind.

Section 7 of 8

22.7 Testing DOM Code with jsdom

Pure functions cover the decisions, but some code is about the page itself: a render function that builds rows from an array, or a button that updates its own text. That code needs document, and document exists only in a browser. Plain Node, where Vitest runs your tests, has no page at all.

jsdom is a package that builds a pretend browser page inside Node: it has a document, elements, querySelector, classList, events, everything your DOM code uses, but nothing is drawn on a screen. Vitest can run a test file inside jsdom. Install it the same way as Vitest:

npm install --save-dev jsdom

Then put this comment as the very first line of any test file that needs a page:

// @vitest-environment jsdom

A test environment is the world the tests run in. Vitest’s default environment is plain Node; this comment switches one file to jsdom. Files without it stay in plain Node, which starts faster.

There is one more step in today’s day22 folder, and it is for the type checker, not for Vitest. This folder’s tsconfig.json is set up for Node, as on Day 13, so the checker does not know the browser’s names:

no-dom-lib.ts
const list = document.createElement("ul");
console.log(list.children.length);
no-dom-lib.ts:1:14 - error TS2584: Cannot find name 'document'. Do you need to change your target library? Try changing the 'lib' compiler option to include 'dom'.

The fix is one setting. In tsconfig.json, add a "lib" list to "compilerOptions" that names the language’s built-in types and the browser’s:

"lib": ["ES2024", "DOM"]

Now the checker knows document, HTMLTableSectionElement and the rest. A Vite project such as Day 18’s already has "DOM" in its "lib" list, so there is nothing to add there. (If you typed no-dom-lib.ts in, delete it now; it has served its purpose.)

Worked example: Testing a render function

renderProducts fills a table body (<tbody>, whose type is HTMLTableSectionElement) with one row per product, like your Day 18 product table:

page/products.ts
export type Product = { name: string; price: number; onSale: boolean };

export function formatPrice(price: number): string {
  return `$${price.toFixed(2)}`;
}

export function renderProducts(body: HTMLTableSectionElement, products: Product[]): void {
  body.textContent = "";
  for (const product of products) {
    const row = document.createElement("tr");
    const name = document.createElement("td");
    name.textContent = product.name;
    const price = document.createElement("td");
    price.textContent = formatPrice(product.price);
    row.append(name, price);
    if (product.onSale) {
      row.classList.add("sale");
    }
    body.append(row);
  }
}

Line 8 clears any old rows first, so calling it again replaces the table instead of adding to it. Lines 10 to 15 build a <tr> with two <td> cells, and lines 16 to 18 add the sale class to products on sale.

page/products.spec.ts
// @vitest-environment jsdom
import { describe, expect, it } from "vitest";
import { renderProducts } from "./products.ts";

const products = [
  { name: "Pen", price: 1.5, onSale: false },
  { name: "Notebook", price: 4, onSale: true },
  { name: "Ruler", price: 2.25, onSale: false },
];

describe("renderProducts", () => {
  it("adds one row per product", () => {
    const body = document.createElement("tbody");
    renderProducts(body, products);
    expect(body.querySelectorAll("tr").length).toBe(3);
  });

  it("shows the name and the price with two decimals", () => {
    const body = document.createElement("tbody");
    renderProducts(body, products);
    const cells = body.querySelectorAll("td");
    expect(cells[0].textContent).toBe("Pen");
    expect(cells[1].textContent).toBe("$1.50");
  });

  it("marks only the products on sale", () => {
    const body = document.createElement("tbody");
    renderProducts(body, products);
    const rows = body.querySelectorAll("tr");
    expect(rows[0].classList.contains("sale")).toBe(false);
    expect(rows[1].classList.contains("sale")).toBe(true);
  });

  it("replaces the old rows when it renders again", () => {
    const body = document.createElement("tbody");
    renderProducts(body, products);
    renderProducts(body, [products[0]]);
    expect(body.querySelectorAll("tr").length).toBe(1);
  });
});

All four tests pass. Each one follows the same three steps:

  1. Set up: create the element the function needs, here an empty <tbody> (line 13). It does not even need to be on the page; jsdom elements work on their own.
  2. Act: call the function (line 14).
  3. Check: look at the result with the same tools you use on a page. querySelectorAll("tr") finds every row, and .length counts them (line 15). Lines 22 and 23 read the cells’ textContent. Lines 30 and 31 ask classList.contains("sale"), which is true or false.

The last test checks a promise that is easy to break: rendering a second time must replace the rows, not add to them.

Events work in jsdom too. Every element has a click() method that fires a click event on it, exactly as if the user had clicked it, so the listeners you attached with addEventListener run. Here is a counter button like the one the Vite starter project comes with:

page/counter.ts
export function setupCounter(button: HTMLButtonElement): void {
  let count = 0;
  const show = (): void => {
    button.textContent = `count is ${count}`;
  };
  button.addEventListener("click", () => {
    count += 1;
    show();
  });
  show();
}
page/counter.spec.ts
// @vitest-environment jsdom
import { describe, expect, it } from "vitest";
import { setupCounter } from "./counter.ts";

describe("setupCounter", () => {
  it("starts at 0", () => {
    const button = document.createElement("button");
    setupCounter(button);
    expect(button.textContent).toBe("count is 0");
  });

  it("adds one on each click", () => {
    const button = document.createElement("button");
    setupCounter(button);
    button.click();
    button.click();
    expect(button.textContent).toBe("count is 2");
  });
});

Both tests pass. The first checks the starting text. The second clicks twice (lines 15 and 16), and each click runs the listener on line 6 of counter.ts, which adds one and shows the new count, so the button reads count is 2.

Watch out

Forgetting the environment comment. Without // @vitest-environment jsdom on line 1, products.spec.ts runs in plain Node, and every test fails at its first line:

ReferenceError: document is not defined

That is a runtime error from Node, not a type error: the code reached a name that does not exist in Node. The "lib" setting in tsconfig.json does not help here, because it only informs the type checker. Add the environment comment as the first line of the test file.

Pause and try

Question 13 · Tracing

Someone deletes line 8 (body.textContent = "";) from products.ts. The last test renders three products, then renders [products[0]] into the same <tbody>. What number does body.querySelectorAll("tr").length give, and does the test pass?

Check your reasoning

It gives 4, and the test fails. Without line 8, the second call does not clear the three rows from the first call; it appends one more. Vitest reports expected 4 to be 1. The other three tests still pass, because each of them renders only once.

Reread 22.7 Testing DOM Code with jsdom if your answer was different.

Question 14 · Multiple choice

render.spec.ts uses document.createElement. It passes npm test, but npm run check (in a Node project like day22) reports Cannot find name 'document' for render.ts. What is the fix?

  1. Add // @vitest-environment jsdom to the top of render.ts.
  2. Add "DOM" to the "lib" list in tsconfig.json.
  3. Run npm install --save-dev jsdom again.
  4. Nothing; the test passes, so the error does not matter.
Check your reasoning

B. The message comes from the type checker, which does not know the browser’s names in a project set up for Node. Adding "DOM" to the "lib" list gives the checker the browser’s types.

  • A is wrong because the environment comment tells Vitest where to run tests; the type checker ignores it. (The test already passes, so the environment is fine.)
  • C is wrong because jsdom is already installed (the test passes) and installing it changes nothing for the checker.
  • D is wrong because a type error is a real problem; Vitest skips type checking, which is why npm run check is a separate step.

Reread 22.7 Testing DOM Code with jsdom if you chose differently.

Section 8 of 8

22.8 Reading a Failing Test

Tests earn their keep when they fail. A failing test is not a disaster; it is Vitest telling you, precisely, where your code and your expectations disagree. You need to be able to read its report quickly.

Suppose someone edits letterGrade in grades/grades.ts and writes > where >= belonged:

if (score > 90) return "A";

Running npm test gives this (the version line, the timing lines and two lines of separator dashes are left out):

 ❯ grades.spec.ts (5 tests | 1 failed) 4ms
   ❯ letterGrade (2)
     × gives an A for exactly 90 2ms

 FAIL  grades.spec.ts > letterGrade > gives an A for exactly 90
AssertionError: expected 'B' to be 'A' // Object.is equality

Expected: "A"
Received: "B"

 ❯ grades.spec.ts:16:29
     14| describe("letterGrade", () => {
     15|   it("gives an A for exactly 90", () => {
     16|     expect(letterGrade(90)).toBe("A");
       |                             ^
     17|   });
     18|

 Test Files  1 failed (1)
      Tests  1 failed | 4 passed (5)

Read it in this order:

  1. Which test? The FAIL line gives the full name: letterGrade > gives an A for exactly 90. A good test name already tells you what is broken: 90 should be an A, and it is not. The × in the list at the top marks the same test.
  2. What was wrong? Expected is the value you wrote in the matcher; Received is what your code actually returned. Your code said "B" for 90.
  3. Where? grades.spec.ts:16:29 is the file, line and column of the failing assertion, and the excerpt below it points at it with ^. That is the line in the test; the bug itself is in the code it calls, letterGrade.
  4. How bad? The summary says 1 failed and 4 passed, so only one behavior broke.

Now reason about the bug: letterGrade(90) returned "B", so the A branch did not fire for exactly 90, but the B branch did. The A condition must exclude 90, which points straight at score > 90. Change it back to >=, run npm test, and all five pass.

There is one more question to ask every time: is the code wrong, or is the test wrong? A test is code too, and it can contain a mistake. Here, the course rule is that 90 is an A, so the test is right and the code is wrong. But if a test expected letterGrade(85) to be "A", the right fix would be the test, not letterGrade. Decide which one matches what the program is supposed to do, and fix that one. Never change a test’s expected value just to make it pass without asking that question.

Different matchers fail with slightly different reports. A number compared with toBe shows the two values as a small difference list, with - before the expected value and + before the received one:

AssertionError: expected 5.99 to be +0 // Object.is equality

- Expected
+ Received

- 0
+ 5.99

(Vitest writes zero as +0 in these messages; it means plain 0.) You will see this report in full in Putting it together.

Pause and try

Question 15 · Tracing

A test fails with this report. What did the code return, what did the test expect, and which test is it?

 FAIL  counter.spec.ts > nextCount > never goes below 0
AssertionError: expected -1 to be +0 // Object.is equality
Check your reasoning

The code returned -1; the test expected 0. The failing test is never goes below 0 in the nextCount group of counter.spec.ts. So nextCount(0, "decrement") went below zero, which means the Math.max(count - 1, 0) guard is missing or wrong.

Reread 22.8 Reading a Failing Test if your answer was different.

Question 16 · Debugging

A teammate adds this test, and it fails with expected 10 to be 11:

it("adds one past the maximum", () => {
  expect(nextCount(10, "increment")).toBe(11);
});

Should you fix nextCount or the test? Explain, and show the fix.

Check your reasoning

Fix the test. The counter’s rule, written in nextCount’s doc comment, is that the count stays between 0 and the maximum (10 by default), so 10 is the correct answer and the test’s expected value is wrong. The corrected test says what the code should do:

it("never goes above the maximum", () => {
  expect(nextCount(10, "increment")).toBe(10);
});

Changing nextCount to return 11 would make the test pass but break the counter.

Reread the “code or test” part of 22.8 Reading a Failing Test if you chose to change the code.

Wrap-up · 1 of 8

Putting it together

A shop’s bug report says: “An order of exactly $50 is still charged $5.99 shipping. Shipping is supposed to be free from $50 up.” Here is how the day’s ideas work together to fix it for good.

1. Keep the logic pure. The shipping rule and the order total live in a module with no page code, so they can be tested directly:

shipping/shipping.ts
export type Order = { subtotal: number; shipping: number; total: number };

/** Shipping is free from $50 up; below that it costs $5.99. */
export function shippingCost(subtotal: number): number {
  if (subtotal < 0) {
    throw new Error("Subtotal cannot be negative");
  }
  return subtotal >= 50 ? 0 : 5.99;
}

export function orderTotal(prices: number[]): Order {
  const subtotal = prices.reduce((sum, price) => sum + price, 0);
  const shipping = shippingCost(subtotal);
  return { subtotal, shipping, total: subtotal + shipping };
}

shippingCost throws for an impossible subtotal; otherwise it returns 0 or 5.99. orderTotal adds the prices with reduce and returns an object with all three amounts.

2. Write tests for the boundary and the bad input, before fixing anything. The bug is at the $50 boundary, so test both sides of it, plus the error and a full order:

shipping/shipping.spec.ts
import { describe, expect, it } from "vitest";
import { orderTotal, shippingCost } from "./shipping.ts";

describe("shippingCost", () => {
  it("charges $5.99 below $50", () => {
    expect(shippingCost(49.99)).toBe(5.99);
  });

  it("is free at exactly $50", () => {
    expect(shippingCost(50)).toBe(0);
  });

  it("rejects a negative subtotal", () => {
    expect(() => shippingCost(-1)).toThrow("cannot be negative");
  });
});

describe("orderTotal", () => {
  it("adds shipping to a small order", () => {
    expect(orderTotal([12, 18])).toEqual({ subtotal: 30, shipping: 5.99, total: 35.99 });
  });

  it("adds nothing to an order of $50", () => {
    expect(orderTotal([20, 30])).toEqual({ subtotal: 50, shipping: 0, total: 50 });
  });
});

Line 6 checks just below the boundary, line 10 exactly on it, and line 14 bad input with toThrow. Lines 20 and 24 use toEqual, because orderTotal returns a new object each time.

3. Read the failures. With the buggy line return subtotal > 50 ? 0 : 5.99;, npm test reports two failures:

 FAIL  shipping.spec.ts > shippingCost > is free at exactly $50
AssertionError: expected 5.99 to be +0 // Object.is equality

- Expected
+ Received

- 0
+ 5.99

 FAIL  shipping.spec.ts > orderTotal > adds nothing to an order of $50
AssertionError: expected { subtotal: 50, shipping: 5.99, …(1) } to deeply equal { subtotal: 50, shipping: +0, …(1) }

- Expected
+ Received

  {
-   "shipping": 0,
+   "shipping": 5.99,
    "subtotal": 50,
-   "total": 50,
+   "total": 55.99,
  }

The first failure reproduces the bug report exactly: at $50, shipping came back 5.99, not 0. The second shows how toEqual reports objects: it lists every property, and marks with - and + only the ones that differ, so you can see that shipping and total are wrong while subtotal is fine. Both failures point at the same place: at exactly 50, subtotal > 50 is false. The test is right (the report says “from $50 up”), so the code is wrong.

4. Fix, then run everything. Change > to >=, as in the file above. npm test now reports 5 passed, and npm run check finds no type errors. A quick run of the program agrees:

shipping/main.ts
import { orderTotal } from "./shipping.ts";

console.log(orderTotal([12, 18]));
console.log(orderTotal([20, 30]));
{ subtotal: 30, shipping: 5.99, total: 35.99 }
{ subtotal: 50, shipping: 0, total: 50 }

The test for exactly $50 stays in the file. If anyone ever brings the bug back, npm test will say so within a second, with the test’s name describing what broke.

Wrap-up · 2 of 8

Common mistakes

Vitest’s messages, and what to do about them:

What Vitest says Usual cause Fix
ReferenceError: describe is not defined The test file does not import from "vitest" Add import { describe, expect, it } from "vitest";
expected [ … ] to be [ … ] and “serializes to the same string” toBe on an array or object Use toEqual
A test fails with the very error you meant to check for expect(f(x)).toThrow() calls f too early expect(() => f(x)).toThrow()
ReferenceError: document is not defined A DOM test running in plain Node First line: // @vitest-environment jsdom
npm test never returns to the prompt The script is vitest, which starts watch mode Press q; make the script vitest run
Every test passes, but npm run check reports errors Vitest does not type-check Fix the type errors; run both commands
Wrap-up · 3 of 8

Vocabulary

Term Definition Example
bug A place where a program does something other than what its author meant A loop that starts at 1 and skips a score
test Code that calls your code with a chosen input and checks the result against the expected answer expect(average([88])).toBe(88)
automated test A test that checks its own result and reports pass or fail, so it can be rerun with one command Everything npm test runs
test runner A program that finds tests, runs them and reports the results Vitest
Vitest A test runner for JavaScript and TypeScript, from the makers of Vite npm install --save-dev vitest
dev dependency A package needed only while building the program, listed under devDependencies vitest, typescript
watch mode Vitest staying open and rerunning tests whenever a file is saved npx vitest
spec Short for specification; a test file that spells out how code should behave grades.spec.ts
test case One test, defined with it: a name and a function it("gives a B for 89", ...)
assertion A claim about a value that must be true for the test to pass expect(x).toBe(3)
matcher The method after expect(...) that compares the actual value with the expected one toBe, toEqual, toThrow
pure function A function whose result depends only on its arguments and that changes nothing outside itself nextCount(3, "increment")
edge case An input at the limit of what the code is meant to handle An empty list, an empty box
boundary A value where the answer changes 90, where a B becomes an A
jsdom A package that builds a pretend browser page inside Node document.createElement("ul") in a test
test environment The world a test file runs in: plain Node by default, or jsdom // @vitest-environment jsdom
Wrap-up · 4 of 8

Summary

  • The type checker checks types, not answers. A program can type-check and still be wrong; tests catch the wrong answers. Run npm test and npm run check, because Vitest does not type-check.
  • Install Vitest as a dev dependency and add "test": "vitest run". Vitest runs every .spec.ts file; describe groups tests, it defines one, and expect(actual) with a matcher checks it.
  • Use toBe for numbers, strings and booleans, toEqual for arrays and objects, and toThrow with an arrow function, expect(() => f(x)), for code that should throw.
  • Keep decisions in pure functions and keep event handlers thin, so the logic can be tested with plain values. Test the edges and the bad input, not just the normal case.
  • DOM code runs in jsdom with // @vitest-environment jsdom: create an element, call your function, and check the result with querySelectorAll, textContent and classList.
  • A failing test tells you which test, the expected and received values, and the line. Then decide whether the code or the test is wrong, and fix that one.
Wrap-up · 5 of 8

Practice

Question 17 · Short answer

Write five tests for Day 16’s parseAge function, including two that expect errors. Use Day 16’s version, moved into a module of its own and exported so a test file can import it:

age/age.ts
export class AgeError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "AgeError";
  }
}

/** Reads a whole-number age from 0 to 130, or throws an AgeError. */
export function parseAge(text: string): number {
  const age = Number(text);
  if (text.trim() === "" || Number.isNaN(age)) {
    throw new AgeError(`"${text}" is not a number`);
  }
  if (!Number.isInteger(age) || age < 0 || age > 130) {
    throw new AgeError(`${age} is not a whole number from 0 to 130`);
  }
  return age;
}
Check your reasoning

One good set of five: a normal age, both ends of the range, and two kinds of bad input.

age/age.spec.ts
import { describe, expect, it } from "vitest";
import { AgeError, parseAge } from "./age.ts";

describe("parseAge", () => {
  it("reads a normal age", () => {
    expect(parseAge("42")).toBe(42);
  });

  it("accepts 0, the lowest age", () => {
    expect(parseAge("0")).toBe(0);
  });

  it("accepts 130, the highest age", () => {
    expect(parseAge("130")).toBe(130);
  });

  it("throws for text that is not a number", () => {
    expect(() => parseAge("forty")).toThrow("is not a number");
  });

  it("throws an AgeError for an age above 130", () => {
    expect(() => parseAge("131")).toThrow(AgeError);
  });
});

All five pass. The first three use toBe with ages that should be accepted, including the boundaries 0 and 130. The last two use toThrow with an arrow function. The fourth checks part of the message. The fifth shows one more thing toThrow accepts: instead of text, you can give it an error class, and the test passes only if the thrown error is an instance of that class (the same check as instanceof). Good extra tests would be "" (which Number turns into 0), "12.5" and "-1". The function behaves the same from a program:

age/main.ts
import { AgeError, parseAge } from "./age.ts";

for (const text of ["42", "forty", "131"]) {
  try {
    console.log(parseAge(text));
  } catch (error) {
    if (error instanceof AgeError) {
      console.log(`Rejected: ${error.message}`);
    }
  }
}
42
Rejected: "forty" is not a number
Rejected: 131 is not a whole number from 0 to 130

Reread 22.4 Matchers: toBe, toEqual and toThrow and 22.6 Edge Cases and Bad Input if your tests did not cover both kinds of input.

Question 18 · Short answer

Move the task list’s add, toggle and remove logic into pure functions and test them.

Check your reasoning

Each function takes the current list and returns a new one, never changing the list it was given:

tasks/tasks.ts
export type Task = { id: number; title: string; done: boolean };

/** A new list with one more task at the end. A blank title changes nothing. */
export function addTask(tasks: Task[], title: string): Task[] {
  const trimmed = title.trim();
  if (trimmed === "") return tasks;
  const nextId = tasks.reduce((max, task) => Math.max(max, task.id), 0) + 1;
  return [...tasks, { id: nextId, title: trimmed, done: false }];
}

/** A new list where the task with this id is flipped between done and not done. */
export function toggleTask(tasks: Task[], id: number): Task[] {
  return tasks.map((task) => (task.id === id ? { ...task, done: !task.done } : task));
}

/** A new list without the task with this id. */
export function removeTask(tasks: Task[], id: number): Task[] {
  return tasks.filter((task) => task.id !== id);
}

addTask uses reduce to find the highest id so far and adds 1 (0 for an empty list, so the first task gets id 1), then builds a new array with spread. toggleTask uses map and copies the matching task with its done flipped, using object spread. removeTask uses filter. The tests cover the normal case, an edge for each, and the promise not to change the input:

tasks/tasks.spec.ts
import { describe, expect, it } from "vitest";
import { addTask, removeTask, toggleTask } from "./tasks.ts";

const start = [
  { id: 1, title: "Buy milk", done: false },
  { id: 2, title: "Walk dog", done: true },
];

describe("addTask", () => {
  it("adds a task that is not done, with the next id", () => {
    expect(addTask(start, "Read")).toEqual([...start, { id: 3, title: "Read", done: false }]);
  });

  it("ignores a blank title", () => {
    expect(addTask(start, "   ")).toEqual(start);
  });

  it("does not change the list it was given", () => {
    addTask(start, "Read");
    expect(start.length).toBe(2);
  });
});

describe("toggleTask", () => {
  it("flips only the task with that id", () => {
    expect(toggleTask(start, 1)).toEqual([
      { id: 1, title: "Buy milk", done: true },
      { id: 2, title: "Walk dog", done: true },
    ]);
  });

  it("flips back when toggled twice", () => {
    expect(toggleTask(toggleTask(start, 2), 2)).toEqual(start);
  });
});

describe("removeTask", () => {
  it("removes the task with that id", () => {
    expect(removeTask(start, 1)).toEqual([{ id: 2, title: "Walk dog", done: true }]);
  });

  it("changes nothing for an id that is not there", () => {
    expect(removeTask(start, 99)).toEqual(start);
  });
});

All seven pass. Because each function returns a new array of new objects, every check uses toEqual, except the length check, which compares a number. A short program shows them working together:

tasks/main.ts
import { addTask, removeTask, toggleTask } from "./tasks.ts";

let tasks = addTask([], "Buy milk");
tasks = addTask(tasks, "Walk dog");
tasks = toggleTask(tasks, 1);
tasks = removeTask(tasks, 2);
console.log(tasks);
[ { id: 1, title: 'Buy milk', done: true } ]

On the page, each handler shrinks to tasks = addTask(tasks, input.value); render(); and the like.

Reread 22.5 Testing Pure Functions if your handlers still made decisions.

Question 19 · Short answer

Write one DOM test that renders a list and checks the number of <li> elements.

Check your reasoning

The render function, using the Task type from exercise 18 (imported with import type, which brings in only the type):

tasks/render.ts
import type { Task } from "./tasks.ts";

export function renderTasks(list: HTMLUListElement, tasks: Task[]): void {
  list.textContent = "";
  for (const task of tasks) {
    const item = document.createElement("li");
    item.textContent = task.title;
    if (task.done) {
      item.classList.add("done");
    }
    list.append(item);
  }
}

The test, which runs in jsdom because of its first line:

tasks/render.spec.ts
// @vitest-environment jsdom
import { expect, it } from "vitest";
import { renderTasks } from "./render.ts";

it("renders one li per task", () => {
  const list = document.createElement("ul");
  renderTasks(list, [
    { id: 1, title: "Buy milk", done: false },
    { id: 2, title: "Walk dog", done: true },
    { id: 3, title: "Read", done: false },
  ]);
  expect(list.querySelectorAll("li").length).toBe(3);
});

It passes. It creates an empty <ul>, renders three tasks into it, and counts the <li> elements with querySelectorAll("li").length. This test has no describe; a single test can stand on its own.

Reread 22.7 Testing DOM Code with jsdom if your test failed with document is not defined.

Wrap-up · 6 of 8

Review questions

Question 20 · Multiple choice

Which test would catch the bug in average-bug.ts from 22.1 (the loop that starts at index 1)?

  1. expect(average([0, 0, 0])).toBe(0);
  2. expect(average([90, 80, 70])).toBe(80);
  3. expect(typeof average([90])).toBe("number");
  4. expect(average([0, 10])).toBe(5);
Check your reasoning

B. The buggy version skips the first score and returns 50, so toBe(80) fails and exposes the bug.

  • A is wrong because skipping a 0 changes nothing: the buggy version also returns 0 and the test passes.
  • C is wrong because the buggy version still returns a number; this test checks only the type, which the type checker already guarantees.
  • D is wrong because the skipped first score is 0: the buggy version adds only 10, divides by 2, and returns 5, so the test passes.

The lesson: a test only catches a bug if the bug changes the answer for that input. When the first score is 0, skipping it changes nothing, so A and D cannot see the bug, and C checks only the type, which the checker already guarantees.

Reread 22.1 Why Test and 22.6 Edge Cases and Bad Input.

Question 21 · Tracing

Which of these three tests pass?

it("one", () => {
  expect({ name: "Pen", price: 2 }).toEqual({ price: 2, name: "Pen" });
});

it("two", () => {
  expect({ name: "Pen", price: 2 }).toBe({ name: "Pen", price: 2 });
});

it("three", () => {
  expect(letterGrades([])).toEqual([]);
});
Check your reasoning

One and three pass; two fails.

  • One: toEqual compares the properties, not the order they were written in. Both objects have name "Pen" and price 2, so they are equal.
  • Two: toBe asks whether they are the same object. They are two different object literals, so it fails with “serializes to the same string”, like the array in 22.4.
  • Three: letterGrades([]) maps an empty array, which gives a new empty array, and toEqual([]) compares contents: no elements on either side, so it passes.

Reread 22.4 Matchers: toBe, toEqual and toThrow if your answer was different.

Question 22 · Short answer

A sign-up form’s submit handler reads an email input, checks that it contains @ and has no spaces, shows an error message next to the field if not, and otherwise adds the email to a list on the page. Describe how you would restructure this code so the checking can be tested, and list three tests you would write for the part you moved.

Check your reasoning

Move the check into a pure function, for example validateEmail(text: string): string | null, which returns an error message, or null when the email is fine. The handler keeps the page work: read the input, call validateEmail, then show the message or add the email and render.

Three good tests:

  • A normal address such as "ana@mail.example" gives null (toBe(null)).
  • A missing @, such as "ana.mail.example", gives a message.
  • An address with a space, such as "ana @mail.example", gives a message (and "" is a good fourth edge case).

A good answer moves the decision into a pure function with plain inputs and outputs, leaves page work in the handler, and tests a normal value plus at least two kinds of bad input.

Reread 22.5 Testing Pure Functions and 22.6 Edge Cases and Bad Input.

Question 23 · Tracing

A test run ends with this summary. How many it tests ran, how many failed, and how many .spec.ts files had at least one failure?

 Test Files  1 failed | 2 passed (3)
      Tests  2 failed | 14 passed (16)
Check your reasoning

16 tests ran (the number in brackets), 2 failed, and 1 test file had a failure; the other 2 files passed completely. Both failing tests are therefore in the same file. The FAIL lines above the summary name them.

Reread 22.3 describe, it and expect and 22.8 Reading a Failing Test.

Question 24 · Debugging

This DOM test fails with ReferenceError: document is not defined. Find the problem and fix it.

import { expect, it } from "vitest";
import { renderTasks } from "./render.ts";

it("renders nothing for an empty list", () => {
  const list = document.createElement("ul");
  renderTasks(list, []);
  expect(list.querySelectorAll("li").length).toBe(0);
});
Check your reasoning

The file runs in Vitest’s default environment, plain Node, which has no document. Add the environment comment as the very first line:

// @vitest-environment jsdom
import { expect, it } from "vitest";
import { renderTasks } from "./render.ts";

Now the test runs in jsdom, document.createElement works, and the test passes: an empty list renders no <li> elements. The ReferenceError was a runtime error, so changing types would not have fixed it.

Reread 22.7 Testing DOM Code with jsdom if you missed it.

Question 25 · Short answer

In Putting it together, the tests were written and run before the bug was fixed, and they failed. Give two reasons it is worth seeing a new test fail before you fix the code.

Check your reasoning
  • It proves the test can catch the bug. A test that passes on the buggy code is checking something else (or nothing), like the matcher-less test in question 6.
  • It reproduces the bug report exactly, so when the test passes after the fix, you know the reported problem, not a different one, is gone. And the test stays in the file to stop the bug coming back.

A good answer mentions both: the failure shows the test really checks the bug, and the passing run afterward confirms the fix.

Reread Putting it together and 22.8 Reading a Failing Test.

Wrap-up · 7 of 8

Go further

The Vitest guide shows more ways to run and organize tests, and the expect reference lists every matcher, including toBeCloseTo for decimal results and .not for “should not”: Vitest: Getting Started and Vitest: expect.

Wrap-up · 8 of 8

Reflection

  • I can explain which bugs the type checker cannot catch and why tests are still needed. Reread
  • I can install Vitest, add a test script, and run my tests with npm test. Reread
  • I can write a test file with describe, it and expect. Reread
  • I can choose between toBe, toEqual and toThrow, and pass toThrow a function. Reread
  • I can move logic out of an event handler into a pure function and test it. Reread
  • I can list the edge cases and bad input a function should be tested with. Reread
  • I can test DOM code in the jsdom environment. Reread
  • I can read a failing test report and decide whether the code or the test is wrong. Reread