| | |

Vitest 19 🧪 Parameterized Tests — test.each for Data-Driven Cases

⏱️ Estimated read: 9 min | |

A parameterized test is a single test declaration that runs once per row in a data table. Vitest’s form is test.each(rows)(name, fn), and the rows are an array of arrays, an array of objects, or a tagged template literal. The table replaces the copy-pasted test bodies that differ only in the input and the expected value, and the reporter shows one test per row with the row’s values interpolated into the name—which means a failure identifies the failing input, not just the function under test.

This chapter covers the three test.each forms, the format specifiers that interpolate the row into the test name, and the describe.each variant that runs a whole block per row. The sections that follow walk through the array form, the object form, and the tagged template that keeps the table readable.

Key point: test.each(rows)(name, fn) runs the test once per row; the array form spreads the row into the callback’s arguments, the object form passes the row as an object, and the %s, %i, %o, and %j specifiers interpolate the values into the test name so a failure names the failing input.


a. The array form and the format specifiers

The array form is the most common. The rows are an array of arrays, and each row is spread into the callback’s arguments. The %s, %i, %f, %o, %j, %#, and %% specifiers interpolate the row’s values into the test name .

import { test, expect } from "vitest";

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

The %i is the integer format, %s is the string, %f is the float, %o is the object, %j is the JSON, %# is the row index, and %% is a literal percent sign . The specifiers are consumed in order, so the first %i takes the first argument and the second %i takes the second. The %# is the zero-based row index, which is useful for a name that includes the position.

The $ prefix is the object form’s specifier. In an array row, $ is not available; in an object row, $name interpolates the property’s value.

test.each([
  { input: "1", expected: 1 },
  { input: "2", expected: 2 },
])("parses $input to $expected", ({ input, expected }) => {
  expect(parseInt(input, 10)).toBe(expected);
});

The $input and $expected reference the object’s properties by name, which makes the test name independent of the argument order. The object form is the clearer form when the row has more than two or three values, because the name references the meaning rather than the position.


b. The test.each variants and the callback signature

The callback’s signature depends on the row’s shape. An array row spreads the values, and the callback receives them as separate arguments. An object row passes the object, and the callback receives it as a single argument, which is why the destructure ({ input, expected }) is the common pattern.

// Array row: spread arguments
test.each([[1, 2, 3]])("add(%i, %i) = %i", (a, b, expected) => { ... });

// Object row: single argument
test.each([{ a: 1, b: 2, expected: 3 }])("add($a, $b) = $expected", ({ a, b, expected }) => { ... });

The tagged template form is the third variant. The table is a template literal with a header row, and the rows follow. The header names become the object’s keys, and the callback receives the row as an object.

test.each`
  a    | b    | expected
  ${1} | ${2} | ${3}
  ${2} | ${2} | ${4}
`("add($a, $b) = $expected", ({ a, b, expected }) => {
  expect(a + b).toBe(expected);
});

The tagged template is the most readable form for a table with named columns. The header row is the property names, and the ${} expressions are the values. The formatter parses the template, and the callback receives the object. The $ specifiers work the same way as in the object form.

The test.skip.each, test.only.each, test.concurrent.each, and test.sequential.each are the variants that combine the table with the modifiers. The skip and only are the common cases, and the concurrent and sequential are for the async tests that need the execution mode.


c. The describe.each and the nested block

The describe.each runs a whole block of tests per row. The callback receives the row’s values, and the tests inside the block use them. The pattern is for a set of tests that share a row’s input—a component that is tested with three different props, a function that is tested with three different roles.

describe.each([
  { role: "admin", canEdit: true },
  { role: "viewer", canEdit: false },
])("$role", ({ role, canEdit }) => {
  test("has the expected permission", () => {
    expect(canEdit(role)).toBe(canEdit);
  });

  test("renders the role", () => {
    render(<RoleBadge role={role} />);
    expect(screen.getByText(role)).toBeInTheDocument();
  });
});

The describe.each is the table at the block level, and the test.each is the table at the case level. The two compose: a describe.each with a test.each inside runs the inner table for every outer row, which is the pattern for a matrix of inputs and cases.

The nested describe.each with the $role in the name produces a block name per row, and the test names inside the block are prefixed by the row’s name. The reporter shows the full path, which is how the failing role is identified.

The test.each with an empty array runs zero tests. A table that is generated from a fixture that happens to be empty produces a suite with no tests in that block, which is the behavior the --passWithNoTests flag addresses at the run level. The empty table is a silent gap, and the test.each does not warn.


Complete Example Session

// ============================================
// PART 1: THE ARRAY FORM
// ============================================
import { test, expect, describe } from "vitest";

test.each([
  [1, 1, 2],
  [1, 2, 3],
  [2, 2, 4],
])("add(%i, %i) = %i", (a, b, expected) => {
  expect(a + b).toBe(expected);
});

// ============================================
// PART 2: THE OBJECT FORM
// ============================================
test.each([
  { input: "1", expected: 1 },
  { input: "2", expected: 2 },
  { input: "", expected: 0 },
])("parses '$input' to $expected", ({ input, expected }) => {
  expect(parseInt(input || "0", 10)).toBe(expected);
});

// ============================================
// PART 3: THE TAGGED TEMPLATE
// ============================================
test.each`
  a    | b    | expected
  ${1} | ${2} | ${3}
  ${2} | ${2} | ${4}
`("add($a, $b) = $expected", ({ a, b, expected }) => {
  expect(a + b).toBe(expected);
});

// ============================================
// PART 4: THE describe.each
// ============================================
describe.each([
  { role: "admin", canEdit: true },
  { role: "viewer", canEdit: false },
])("$role", ({ role, canEdit }) => {
  test("has the expected permission", () => {
    expect(canEdit(role)).toBe(canEdit);
  });
});

// ============================================
// PART 5: THE ERROR CASE
// ============================================
test.each([
  { input: "", message: "required" },
  { input: "abc", message: "numeric" },
])("rejects '$input' with $message", ({ input, message }) => {
  expect(() => parsePort(input)).toThrow(message);
});

The parts covered the array form, the object form, the tagged template, the describe.each, and the error case.


Quick Reference

The Three Forms

FormRowsCallback
Array[[1, 2, 3]]Spread arguments
Object[{ a: 1, b: 2 }]Single object
Template`a | b | c`Single object

Format Specifiers

SpecifierValue
%sString
%iInteger
%fFloat
%oObject
%jJSON
%#Row index
$propObject property
%%Literal %

Variants

VariantEffect
test.skip.eachSkip each row
test.only.eachOnly these rows
test.concurrent.eachRun rows concurrently
describe.eachBlock per row

Best Practices

✅ Do This:

// Use the object form for named values
test.each([{ a: 1, b: 2, expected: 3 }])("add($a, $b) = $expected", ({ a, b, expected }) => { ... }); // ✅

// Use the tagged template for a readable table
test.each`
  a    | b    | expected
  ${1} | ${2} | ${3}
`("add($a, $b) = $expected", ({ a, b, expected }) => { ... }); // ✅

// Use describe.each for a shared block
describe.each(roles)("$role", ({ role }) => { ... });         // ✅

❌ Don’t Do This:

// Copy the test body per case
test("add 1 + 1", () => { ... });
test("add 1 + 2", () => { ... }); // use each                    // ❌

// Use the array form with more than three values
test.each([[1, 2, 3, 4, 5, 6]])("%i", (a) => { ... });         // ❌

// Assume the empty table fails
test.each([])("%i", () => { ... }); // runs zero tests          // ❌

Common Pitfalls

PitfallWhy It HappensFix
Name shows the wrong valueSpecifier orderMatch the order to the arguments
Object row is undefinedArray row usedUse the object or template form
Empty table silently passesZero rowsCheck the table is non-empty
$prop not interpolatedArray rowUse the object form

Real-World Examples

1. Array form

test.each([[1, 2, 3]])("add(%i, %i) = %i", (a, b, e) => { ... });

2. Object form

test.each([{ a: 1, b: 2 }])("add($a, $b)", ({ a, b }) => { ... });

3. Tagged template

test.each`
  a    | b
  ${1} | ${2}
`("add($a, $b)", ({ a, b }) => { ... });

4. String table

test.each(["1", "2", "3"])("parses %s", (input) => { ... });

5. describe.each

describe.each(roles)("$role", ({ role }) => { ... });

6. Skip

test.skip.each(rows)("...", fn);

7. Only

test.only.each(rows)("...", fn);

8. Concurrent

test.concurrent.each(rows)("...", fn);

9. Row index

test.each(rows)("row %#", (_row, index) => { ... });

10. Error table

test.each([{ input: "", message: "required" }])("rejects", ({ input, message }) => { ... });

Visual

The Array Form

┌─────────────────────────────────────────────────────────┐
│  test.each([                                            │
│    [1, 1, 2],                                           │
│    [1, 2, 3],                                           │
│  ])("add(%i, %i) = %i", (a, b, expected) => { ... });  │
│                                                         │
│  Generates:                                             │
│  ✓ add(1, 1) = 2                                        │
│  ✓ add(1, 2) = 3                                        │
└─────────────────────────────────────────────────────────┘

The Object Form

┌─────────────────────────────────────────────────────────┐
│  test.each([                                            │
│    { a: 1, b: 2, expected: 3 },                         │
│  ])("add($a, $b) = $expected", ({ a, b, expected }) => { ... });│
│                                                         │
│  Generates:                                             │
│  ✓ add(1, 2) = 3                                        │
└─────────────────────────────────────────────────────────┘

The Tagged Template

┌─────────────────────────────────────────────────────────┐
│  test.each`                                             │
│    a    | b    | expected                               │
│    ${1} | ${2} | ${3}                                   │
│    ${2} | ${2} | ${4}                                   │
│  `("add($a, $b) = $expected", ({ a, b, expected }) => { ... });│
│                                                         │
│  The header row is the property names.                  │
└─────────────────────────────────────────────────────────┘

The describe.each

┌─────────────────────────────────────────────────────────┐
│  describe.each([                                        │
│    { role: "admin", canEdit: true },                    │
│    { role: "viewer", canEdit: false },                  │
│  ])("$role", ({ role, canEdit }) => {                   │
│    test("has the permission", () => { ... });           │
│  });                                                    │
│                                                         │
│  Generates a block per row.                             │
└─────────────────────────────────────────────────────────┘

Summary

ItemValue
Array formtest.each([[1, 2, 3]])
Object formtest.each([{ a: 1 }])
Template formtest.each`a | b`
Specifiers%s, %i, %f, %o, %j, %#, $prop
Block formdescribe.each
Variantsskip, only, concurrent

Key takeaways:

  • test.each runs the test once per row. The array form spreads the row into the callback’s arguments, the object form passes the row as a single object, and the tagged template is the readable table with a header row .
  • The format specifiers interpolate the row into the test name. %i, %s, %o, %j, and %# reference the row’s values by position, and $prop references the object’s property by name. A failure names the failing input, not just the function.
  • The object and template forms are clearer for a row with meaning. The array form’s positional arguments are fine for two or three values, and the named form is better when the row has more.
  • describe.each is the block-level table. The callback receives the row’s values, and the tests inside the block use them, which is the pattern for a set of tests that share a row’s input .
  • The empty table runs zero tests without a warning. A table generated from a fixture that happens to be empty produces a suite with no tests in that block, which is a silent gap rather than a failure.

Remember: A parameterized test is one declaration and many executions. The table is the data, the specifiers are the names, and the row is the input. Use the object or template form when the row has meaning, the array form when it is positional, and describe.each when the whole block varies. The failure names the row, which is the reason the table is worth writing.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!