Unit tests

Test boundaries with tables

Cover a family of related edge cases with data-driven tests while preserving useful case names and diagnostics.

8 minute lesson

~~~

Validation bugs live near boundaries: empty versus one character, maximum length versus one over, and valid versus impossible years.

A table keeps the setup consistent and makes missing cases visible. Give each row a descriptive name; do not hide an entire product specification in a clever loop.

const cases = [
  {
    name: 'rejects an empty title',
    input: { title: '', author: 'A' },
    field: 'title'
  },
  {
    name: 'rejects a blank author',
    input: { title: 'Dune', author: '  ' },
    field: 'author'
  }
]

for (const { name, input, field } of cases) {
  test(name, () => {
    const result = validateBook(input)
    assert.equal(result.ok, false)
    assert.equal(result.field, field)
  })
}

A boundary is where behavior changes. If titles allow 1 through 200 characters, the informative values are 0, 1, 200, and 201—not an arbitrary middle value such as 73. For a publication year, also ask whether the rule is inclusive, whether numeric strings are accepted, and what happens to null, an empty string, a decimal, or NaN.

Name every row so the failure identifies the missing rule. A single test containing a loop can stop at the first bad row and hide later failures. Creating one test per row preserves independent diagnostics while keeping the cases together.

Tables work best when all rows exercise the same decision. If one row tests title validation and another tests a repository timeout, their setup and expected evidence are different; separate tests will be clearer. Also include at least one valid row. A validator that rejects every input can make an all-invalid table look correct.

Add valid minimum and maximum values plus one invalid value on each side of every boundary. Temporarily change <= to < in the implementation and confirm that a boundary case, not a generic example, catches the mistake.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →