Reading at scale

Lesson 18 Tests as the spec

6 min read · JavaScript · Quiz

what a test really checks, and the missing test

What you'll learn

  • Read test names as a spec
  • Judge whether an assertion could really fail
  • Spot the missing test

Tests are the one place that says what the code is supposed to do. But a test can pass and prove nothing, so read each one twice.

The idea

Read the test names like a spec. Each name is a promise about the code. Then read the assertion, the line that can fail, and ask: would this fail if the code were wrong? A weak assertion such as assert.ok(result) passes for almost any answer.

Last, look for the missing test: something the code does that no test name mentions, such as an unknown code, an empty list or a zero. A quick trick: break the code on purpose, change a number, and see which tests notice.

discounts.test.js
1const test = require("node:test");2const assert = require("node:assert");3const { applyDiscount } = require("../src/discounts");45test("VIP gets 25 percent off", () => {6  assert.strictEqual(applyDiscount({ total: 100 }, "VIP"), 75);7});89test("SPRING gets 10 percent off", () => {10  const result = applyDiscount({ total: 100 }, "SPRING");11  assert.ok(result);12});1314test("does not change the order", () => {15  const order = { total: 100 };16  applyDiscount(order, "VIP");17  assert.strictEqual(order.total, 100);18});
  1. Line 5 The names read as a spec: VIP 25 percent, SPRING 10 percent, and the input isn't changed.
  2. Line 6 A strong assertion: an exact value. If the VIP rate is wrong, this fails.
  3. Line 11 A weak assertion: any non-zero result passes. A SPRING discount of 0%, or 90%, would still pass.
  4. Line 18 The end of the file. Nothing here mentions an unknown code, a total of 0 or a negative total. Those promises are missing.

Take away

  • Read the test names like a spec: each one is a promise.
  • Read the assertion and ask: would this fail if the code were wrong?
  • Look for the missing test: a promise the code makes that no test names.

Quiz: test yourself

7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.