Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 30 ยท Snapshots and Tables

Table-Driven Tests with test.each

Run one Jest test over many inputs with test.each and describe.each: array tables, tagged template tables, printf title formatting, edge-case tables and a runnable stand-in.

Look at this set of tests:

JavaScript
test("adds 1 + 1", () => { expect(add(1, 1)).toBe(2); });
test("adds 2 + 3", () => { expect(add(2, 3)).toBe(5); });
test("adds -1 + 1", () => { expect(add(-1, 1)).toBe(0); });

Each test has the same shape. Only the numbers change. Copying and pasting the body is noisy, and a typo in one copy is easy to miss. A table-driven test keeps the logic in one place and lists the cases as data. Jest supports this with test.each (and describe.each), and every row shows up as its own test in the report, so a failure tells you exactly which row broke.

This lesson shows the array and tagged-template styles, how test titles are formatted, how to design an edge-case table, and when a table is the wrong choice. The real test.each needs Jest, so the Jest code is read-only. The stand-in implements the same idea in a few lines of plain Node.js so you can see what Jest does with a table.

One body, many rows

Table Rows of inputs and expected outputs.
One test body The same assertions run for every row.
Titles Each row gets its own readable name.

A failure names the exact row.

1 / 2

test.each with arrays

Pass an array of rows. Each row is an array whose items become the arguments of your test function:

JavaScript
test.each([
  [1, 1, 2],
  [2, 3, 5],
  [-1, 1, 0],
])("add(%i, %i) returns %i", (a, b, expected) => {
  expect(add(a, b)).toBe(expected);
});

Jest creates three tests and formats the title for each row:

TEXT
โœ“ add(1, 1) returns 2
โœ“ add(2, 3) returns 5
โœ“ add(-1, 1) returns 0

If you pass a one-dimensional array of plain values, each value is a single argument:

JavaScript
test.each([0, 1, 2, 3])("%i is less than 4", (n) => {
  expect(n).toBeLessThan(4);
});

Title formatting

The title is a template that uses printf-style placeholders. The values are taken from the row in order:

Placeholder Meaning
%s String (any value converted to a string)
%d and %i Number / integer
%f Floating-point number
%j JSON
%o Object (with details)
%p Pretty-format of the value
%# Index of the row (starting at 0)
%% A literal percent sign

If there are more values in a row than placeholders, the extra values are passed to the function but not shown in the title. Good titles make the failure report readable: isLeapYear(1900) is false beats case 3.

Tagged template tables

For tables with several named columns, the tagged-template form is easier to read because the first row names the columns:

JavaScript
test.each`
  a     | b     | expected
  ${1}  | ${1}  | ${2}
  ${2}  | ${3}  | ${5}
  ${-1} | ${1}  | ${0}
`("add($a, $b) returns $expected", ({ a, b, expected }) => {
  expect(add(a, b)).toBe(expected);
});

The header cells (a, b, expected) become properties of one object that your function receives, and $name in the title is replaced by the cell value. Values go inside ${...}, so they can be numbers, strings, objects, functions or anything else. You can reach into objects in the title with $user.name. This style shines when a row has more than three values or contains objects, because each value has a label.

describe.each

describe.each runs a whole group of tests once per row:

JavaScript
describe.each([
  ["USD", "$"],
  ["EUR", "โ‚ฌ"],
  ["GBP", "ยฃ"],
])("formatPrice in %s", (currency, symbol) => {
  test("starts with the symbol", () => {
    expect(formatPrice(5, currency)).toMatch(new RegExp(`^\\${symbol}`));
  });

  test("shows two decimals", () => {
    expect(formatPrice(5, currency)).toMatch(/\.00$/);
  });
});

Use it when several tests share the same setup per case. Hooks such as beforeEach inside the describe.each callback run for every row. See Setup and Teardown Hooks for the order they run in.

Like test, the table versions support .only and .skip (test.only.each, describe.skip.each), and there is test.concurrent.each for async cases that may run in parallel.

Designing a good table

A table is only as good as its rows. Think about categories of input, not just typical examples:

  • Normal cases: the common values.
  • Boundaries: the smallest and largest valid value, and the values on each side of a limit (for a limit of 18, try 17, 18 and 19).
  • Empty and zero: "", [], 0, null.
  • Invalid input: things that should throw or return an error.
  • Special cases: leap years, negative numbers, Unicode, very long input.

Here is a table for a function that decides whether a year is a leap year, including the tricky century rules:

JavaScript
test.each`
  year    | expected | reason
  ${2024} | ${true}  | ${"divisible by 4"}
  ${2023} | ${false} | ${"not divisible by 4"}
  ${1900} | ${false} | ${"century not divisible by 400"}
  ${2000} | ${true}  | ${"century divisible by 400"}
  ${0}    | ${true}  | ${"year zero is divisible by 400"}
`("isLeapYear($year) is $expected ($reason)", ({ year, expected }) => {
  expect(isLeapYear(year)).toBe(expected);
});

The reason column does not appear in the function's destructuring; it is documentation that shows up in the test title. That is a neat trick for explaining why each row exists.

For tests that must throw, put the expected message in the table. Errors and Custom Matchers shows the toThrow variants.

When not to use a table

  • When each case needs different assertions or setup. A table with if statements in the body is a sign that you should write separate tests.
  • When the expected value is computed with the same formula as the code under test. A table of hard-coded expected values is independent evidence; copying the formula into the test only repeats any bug.
  • When there are only one or two cases. A plain test is clearer.

Stand-in: how a table becomes tests

Here is a small stand-in for test.each. It takes a table, formats each title with printf-style placeholders, runs the body for every row and collects pass/fail results. It is NOT Jest's implementation (no hooks, no async, fewer placeholders), but it shows the key idea: one body, one generated test per row, one clear title per row.

Node.js A mini test.each

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The buggy function fails only for the row where a is 2, and the title with the row index and values points straight at it. If you had written one test with a loop inside, the report would only say "the test failed" and you would have to find which value caused it.

Stand-in: a tagged template table

The tagged-template form is plain JavaScript: a function receives the template strings and the interpolated values. This stand-in parses such a table into row objects and fills $name placeholders in the title, which is the core of what Jest does with the syntax. Again, real Jest has more features (nested property access like $user.name, for example).

Node.js Parsing a tagged template table

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The first template string holds the header row, and each following group of ${...} values is a row. Because the values come from real JavaScript expressions, a cell can hold anything, not only text.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In test.each([[1, 1, 2], [2, 3, 5]])("add(%i, %i) = %i", fn), how many tests does Jest create?

    Each row of the table becomes its own test, so a table with two rows creates two tests.
  2. 2. What does the %# placeholder insert into a test title?

    %# is replaced with the zero-based index of the current row. A literal percent sign is written %%.
  3. 3. In a tagged template table, how does your test function receive the values of a row?

    With the tagged-template form, the header cells become properties of a single object passed to the test function.
  4. 4. Which situation is a poor fit for a table-driven test?

    When every case needs its own steps, the table body fills with conditionals. Separate tests are clearer.

Summary

  • test.each(table)(title, fn) creates one test per row; describe.each creates one group per row.
  • Rows can be arrays (positional arguments) or a tagged template with a header row (one object per row).
  • Use printf placeholders like %s, %i, %p and %#, or $name in tagged templates, to make unique, readable titles.
  • Build tables from categories: normal cases, boundaries, empty values, invalid input and special cases.
  • Skip tables for one or two cases, or when each case needs different steps.

Next, move from writing tests to running them in real projects with Configuring Jest.