Sub topic 9
Covering Many Cases with test.each
A function like add or a validator often needs a dozen checks that differ only in their inputs and expected output. You could copy the same test body twelve times and change the numbers. That works until you need to change the body, and then you edit it twelve times. test.each lets you write the body once and supply the cases as data. Vitest generates one separate test per case, and each one passes, fails and gets reported independently.
This chapter assumes you can write tests with test, it and describe, and that you know the common matchers such as toBe, toEqual and toThrow. You should also be comfortable with destructuring, because most table-driven tests depend on it.
The basic shape
test.each takes a table and returns a function. You call that function with a name template and a test body, just as you would call test.
import { test, expect } from 'vitest'
function add(a, b) {
return a + b
}
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)
})Running npx vitest run reports three tests:
✓ add(1, 1) returns 2
✓ add(2, 3) returns 5
✓ add(-1, 1) returns 0Each row is an array. Vitest spreads the row into the body's arguments, so [2, 3, 5] becomes a = 2, b = 3, expected = 5. The %i placeholders in the name are filled from the same row, from left to right.
A failing row does not stop the other rows from running. If the second row fails, the report names add(2, 3) returns 5 as the failure. That name is the main reason to keep names readable.
Name placeholders
The name template uses printf-style placeholders. Vitest formats each value from the row and puts it into the name in order.
| Placeholder | Formats the value as |
|---|---|
| `%s` | String |
| `%d` | Number |
| `%i` | Integer |
| `%f` | Floating-point number |
| `%j` | JSON |
| `%o` | Object |
| `%#` | Index of the test case (starting at 0) |
| `%%` | A literal percent sign |
%s works for most values. Use %j or %o when a row contains objects or arrays, so the name shows their contents and not [object Object]. %# helps when the values alone do not make names unique.
import { test, expect } from 'vitest'
function isBlank(value) {
return value.trim() === ''
}
test.each([
['', true],
[' ', true],
['\t\n', true],
['a', false],
])('case %#: isBlank(%j) is %s', (input, expected) => {
expect(isBlank(input)).toBe(expected)
})The %j placeholder shows whitespace strings as " " and "\t\n". With %s they would appear as blank gaps in the report.
Rows as objects
When a row has more than two or three values, positional arrays become hard to read. [0, 10, false, 'x'] does not tell you which number is which. You can use objects instead. When the rows are objects, Vitest passes each object to the body as a single argument, and the name template refers to properties with $name.
import { test, expect } from 'vitest'
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max)
}
test.each([
{ value: 5, min: 0, max: 10, expected: 5 },
{ value: -3, min: 0, max: 10, expected: 0 },
{ value: 42, min: 0, max: 10, expected: 10 },
])('clamp($value, $min, $max) -> $expected', ({ value, min, max, expected }) => {
expect(clamp(value, min, max)).toBe(expected)
})Nested properties work with dot paths, such as $user.name. Object rows also protect you from ordering mistakes. If you add a field later, existing rows and the destructuring still match, because nothing depends on position.
The template literal table
Vitest also accepts a tagged template literal laid out like a table. The first line holds the column names, separated by |. Each row after that supplies values through ${} expressions.
import { test, expect } from 'vitest'
function add(a, b) {
return a + b
}
test.each`
a | b | expected
${1} | ${1} | ${2}
${2} | ${3} | ${5}
${-1} | ${1} | ${0}
`('returns $expected when $a is added to $b', ({ a, b, expected }) => {
expect(add(a, b)).toBe(expected)
})Each row reaches the body as an object keyed by the column names, the same as with object rows. This format reads well for short numeric tables. It is easy to break, though: every value must be wrapped in ${}, and a row with a missing cell causes an error. For anything larger, object rows are usually easier to maintain.
Grouping with describe.each
describe.each repeats a whole group of tests for each row. Use it when several assertions apply to every variant, such as each supported currency or each implementation of the same interface.
import { describe, test, expect } from 'vitest'
function formatPrice(amount, currency) {
return new Intl.NumberFormat('en-US', { style: 'currency', currency }).format(amount)
}
describe.each([
{ currency: 'USD', symbol: '$' },
{ currency: 'EUR', symbol: '€' },
])('formatPrice in $currency', ({ currency, symbol }) => {
test('includes the currency symbol', () => {
expect(formatPrice(10, currency)).toContain(symbol)
})
test('shows two decimal places', () => {
expect(formatPrice(10, currency)).toMatch(/10\.00/)
})
})This produces four tests in two groups. The modifiers you know from plain tests combine with .each too: test.skip.each, test.only.each, test.concurrent.each and describe.skip.each.
test.for: no spreading, with test context
Vitest 2 and later also provide test.for. It takes the same tables and placeholders, but it handles arguments differently:
- An array row is passed as one argument and is not spread. You destructure it yourself.
- The second argument is the test context, which includes a local
expect. A localexpectmatters for concurrent tests, because it ties assertions to the correct test.
import { test } from 'vitest'
function add(a, b) {
return a + b
}
test.concurrent.for([
[1, 1, 2],
[2, 3, 5],
])('add(%i, %i) -> %i', ([a, b, expected], { expect }) => {
expect(add(a, b)).toBe(expected)
})Use test.each for ordinary tables. Use test.for when you need the context, or when you run the cases concurrently.
Gotchas and common errors
Spreading surprises
test.each spreads a row only if the row is an array. If the table is [1, 2, 3], each number arrives as the single argument. If you want to pass an array as one value, wrap it in another array: [[[1, 2], 3]] passes [1, 2] and 3. Mixing array rows and plain-value rows in one table gives confusing argument lists, so keep every row the same shape.
Tables are built at collection time
Vitest evaluates the table while it collects tests, which happens before any beforeEach or beforeAll hook runs. A table that refers to a variable assigned in a hook sees undefined:
import { test, expect, beforeAll } from 'vitest'
let config
beforeAll(() => {
config = { limit: 10 }
})
// Wrong: config is still undefined when this table is built.
// test.each([[config]])('uses %o', (c) => { ... })
test.each([[10]])('limit is %i', (limit) => {
expect(config.limit).toBe(limit) // reading config inside the body is fine
})Keep tables to literal data. Read hook-prepared state inside the body.
Shared mutable rows
If several rows reference the same object and the code under test mutates it, the rows affect each other and the result depends on run order. Create a new object for each row, or have the body copy its input before using it.
Duplicate names
Two rows that produce the same name make failures ambiguous. They also make -t name filters match more than you intended. Include enough placeholders, or %#, to make every name unique.
Too much logic in the body
When the body starts to branch with if (expected === 'error'), the table is mixing two behaviors. Split it into two tables, one for return values and one for thrown errors. Each body then stays a straight line with a single kind of assertion.
import { test, expect } from 'vitest'
function parseAge(text) {
const n = Number(text)
if (!Number.isInteger(n) || n < 0) {
throw new Error(`Invalid age: ${text}`)
}
return n
}
test.each([
['0', 0],
['42', 42],
])('parseAge(%j) returns %i', (input, expected) => {
expect(parseAge(input)).toBe(expected)
})
test.each(['-1', '3.5', 'abc'])('parseAge(%j) throws', (input) => {
expect(() => parseAge(input)).toThrow('Invalid age')
})The second table uses plain string rows. Each string reaches the body as its single argument.
When to use a table
| Situation | Choice |
|---|---|
| Same assertion, inputs vary | `test.each` |
| Many fields per case | Object rows with `$name` |
| Several tests per variant | `describe.each` |
| Concurrent cases or need test context | `test.for` |
| Setup or assertions differ per case | Separate `test` calls |
Exercise
You write test.each([[1, 2], [3, 4]])('pair %o', (pair) => { expect(pair).toHaveLength(2) }). Both tests fail. Why, and what are two ways to fix it?
Show answer
test.each spreads each array row, so pair receives only the first number (1 or 3), and a number has no length. One fix is to wrap each row, test.each([[[1, 2]], [[3, 4]]]), so the inner array arrives as the single argument. The other is to switch to test.for, which does not spread rows. The body then receives [1, 2] as its first argument and the test context as its second.
Exercise
Rewrite a set of tests for a function isEven(n) as one test.each with object rows covering 0, 7, -4 and 11. Each test name should show the input and the expected result.
Show answer
test.each([{ n: 0, expected: true }, { n: 7, expected: false }, { n: -4, expected: true }, { n: 11, expected: false }])('isEven($n) is $expected', ({ n, expected }) => { expect(isEven(n)).toBe(expected) })
Exercise
A table refers to a users array that is filled in a beforeAll hook, and every generated test receives undefined. Explain the cause and the fix.
Show answer
Vitest builds the table while it collects tests, which happens before any hook runs, so users is still empty or undefined at that point. Put literal data in the table, such as user ids or indexes, and look up the prepared users inside the test body, which runs after beforeAll.