Parameterized tests

suggest change

A parameterized test (also called a table-driven or data-driven test) runs the same test logic against many inputs. Instead of copy-pasting a test five times with different values, you describe the cases as data and generate one test per case.

Benefits:

The built-in node:test runner has no special API for this, and doesn't need one: tests are registered by plain function calls, so a for loop is enough. Mocha works the same way. Jest and Vitest add test.each helpers.

Examples below were run with Node.js 24, Mocha 12 and Vitest 5.

A function to test

// src/slugify.js
export function slugify(text, { maxLength = 60 } = {}) {
  if (typeof text !== 'string') {
    throw new TypeError('text must be a string');
  }
  return text
    .normalize('NFKD')
    .replace(/[\u0300-\u036f]/g, '') // strip accents
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-+|-+$/g, '')
    .slice(0, maxLength)
    .replace(/-+$/, '');
}

package.json has "type": "module" and "test": "node --test".

A loop over cases with node:test

// test/slugify.test.js
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { slugify } from '../src/slugify.js';

const cases = [
  { input: 'Hello World', expected: 'hello-world' },
  { input: '  trim me  ', expected: 'trim-me' },
  { input: 'Crème brûlée', expected: 'creme-brulee' },
  { input: 'C++ & C#', expected: 'c-c' },
  { input: '---', expected: '' },
];

for (const { input, expected } of cases) {
  test(`slugify(${JSON.stringify(input)}) -> ${JSON.stringify(expected)}`, () => {
    assert.equal(slugify(input), expected);
  });
}
$ node --test
✔ slugify("Hello World") -> "hello-world" (0.6111ms)
✔ slugify("  trim me  ") -> "trim-me" (0.5544ms)
✔ slugify("Crème brûlée") -> "creme-brulee" (0.102ms)
✔ slugify("C++ & C#") -> "c-c" (0.0589ms)
✔ slugify("---") -> "" (0.0657ms)
ℹ tests 5
ℹ suites 0
ℹ pass 5
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 58.4524

The loop runs when the file is loaded and registers 5 independent tests. JSON.stringify in the name makes whitespace and empty strings visible, which plain ${input} would hide.

Why not a loop inside a single test

A common shortcut is to put the loop inside one test:

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { parseDuration } from '../src/duration.js';

test('parseDuration (one test, loop inside)', () => {
  const cases = [
    ['250ms', 250],
    ['2s', 2000],
    ['1.5m', 9000],   // wrong: should be 90000
    ['1h', 3600000],  // never checked
  ];
  for (const [input, expected] of cases) {
    assert.equal(parseDuration(input), expected, `parseDuration(${input})`);
  }
});
✖ parseDuration (one test, loop inside) (1.6661ms)
...
  AssertionError [ERR_ASSERTION]: parseDuration(1.5m)

  90000 !== 9000

The first failing assertion throws and ends the test, so '1h' is never checked. You get one failure even when several cases are broken, and you must add a custom message to know which case it was. Generating one test per case avoids both problems. Keep the inner loop only for quick checks where cases are not worth reporting individually.

Grouping with describe and descriptive names

Wrap generated tests in describe to group them in the output. When the case is complicated, give it a name field instead of building a name from the data:

import { describe, test } from 'node:test';
import assert from 'node:assert/strict';
import { slugify } from '../src/slugify.js';

describe('slugify', () => {
  const cases = [
    ['Hello World', 'hello-world'],
    ['Crème brûlée', 'creme-brulee'],
    ['C++ & C#', 'c-plus-plus-c-sharp'], // wrong expectation on purpose
  ];

  for (const [input, expected] of cases) {
    test(`${JSON.stringify(input)} -> ${JSON.stringify(expected)}`, () => {
      assert.equal(slugify(input), expected);
    });
  }

  const lengthCases = [
    { name: 'cuts at maxLength', input: 'abcdef', maxLength: 3, expected: 'abc' },
    { name: 'no trailing dash after cut', input: 'abc def', maxLength: 4, expected: 'abc' },
    { name: 'default is 60', input: 'x'.repeat(100), expected: 'x'.repeat(60) },
  ];

  for (const { name, input, maxLength, expected } of lengthCases) {
    test(name, () => {
      assert.equal(slugify(input, { maxLength }), expected);
    });
  }

  const invalid = [null, undefined, 42, ['a'], { text: 'a' }];

  for (const value of invalid) {
    test(`throws TypeError for ${typeof value}: ${JSON.stringify(value)}`, () => {
      assert.throws(() => slugify(value), {
        name: 'TypeError',
        message: 'text must be a string',
      });
    });
  }
});
▶ slugify
  ✔ "Hello World" -> "hello-world" (0.6641ms)
  ✔ "Crème brûlée" -> "creme-brulee" (0.1187ms)
  ✖ "C++ & C#" -> "c-plus-plus-c-sharp" (0.6461ms)
  ✔ cuts at maxLength (0.0837ms)
  ✔ no trailing dash after cut (0.0737ms)
  ✔ default is 60 (0.0579ms)
  ✔ throws TypeError for object: null (0.4062ms)
  ✔ throws TypeError for undefined: undefined (0.0838ms)
  ✔ throws TypeError for number: 42 (0.0879ms)
  ✔ throws TypeError for object: ["a"] (0.1154ms)
  ✔ throws TypeError for object: {"text":"a"} (0.0684ms)
✖ slugify (3.3471ms)
ℹ tests 11
ℹ suites 1
ℹ pass 10
ℹ fail 1
...
✖ failing tests:

test at test\slugify.test.js:13:5
✖ "C++ & C#" -> "c-plus-plus-c-sharp" (0.6461ms)
  AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
  + actual - expected

  + 'c-c'
  - 'c-plus-plus-c-sharp'

Things to notice:

Test names must be unique enough to tell cases apart. Two cases with the same name both run, but you won't know which one failed.

Async cases

Each generated test can be async. Use assert.rejects for promises that should fail:

// src/duration.js
const UNITS = { ms: 1, s: 1000, m: 60_000, h: 3_600_000 };

export function parseDuration(str) {
  const match = /^(\d+(?:\.\d+)?)(ms|s|m|h)$/.exec(str.trim());
  if (!match) {
    throw new SyntaxError(`invalid duration: ${JSON.stringify(str)}`);
  }
  return Number(match[1]) * UNITS[match[2]];
}

export async function sleepFor(str) {
  const ms = parseDuration(str);
  await new Promise((resolve) => setTimeout(resolve, ms));
  return ms;
}
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { parseDuration, sleepFor } from '../src/duration.js';

for (const input of ['', '10', '5 days', '-1s', 's']) {
  test(`rejects ${JSON.stringify(input)}`, () => {
    assert.throws(() => parseDuration(input), SyntaxError);
  });
}

for (const [input, expected] of [['5ms', 5], ['0.02s', 20]]) {
  test(`sleepFor(${input}) resolves to ${expected}`, async () => {
    assert.equal(await sleepFor(input), expected);
  });
}

for (const input of ['soon', '1 h']) {
  test(`sleepFor(${input}) rejects`, async () => {
    await assert.rejects(sleepFor(input), { name: 'SyntaxError' });
  });
}
✔ rejects "" (0.2962ms)
✔ rejects "10" (0.0959ms)
✔ rejects "5 days" (0.0699ms)
✔ rejects "-1s" (0.0576ms)
✔ rejects "s" (0.0504ms)
✔ sleepFor(5ms) resolves to 5 (5.198ms)
✔ sleepFor(0.02s) resolves to 20 (31.4778ms)
✔ sleepFor(soon) rejects (0.6136ms)
✔ sleepFor(1 h) rejects (0.1557ms)

Don't forget the await before assert.rejects. Without it the test finishes before the assertion settles.

Skipping or marking individual cases

test() accepts an options object with skip, todo and only. Put those fields in the case data and pass them through:

const cases = [
  { input: 'a b', expected: 'a-b' },
  { input: 'emoji 🎉 party', expected: 'emoji-party' },
  { input: 'tab\there', expected: 'tab-here', skip: 'tabs not decided yet' },
  { input: 'Straße', expected: 'strasse', todo: 'ß is dropped' },
];

for (const { input, expected, skip, todo } of cases) {
  test(`case ${JSON.stringify(input)}`, { skip, todo }, () => {
    assert.equal(slugify(input), expected);
  });
}
✔ case "a b" (0.0767ms)
✔ case "emoji 🎉 party" (0.0781ms)
﹣ case "tab\there" (0.0445ms) # tabs not decided yet
⚠ case "Straße" (0.6465ms) # ß is dropped
ℹ tests 4
ℹ pass 2
ℹ fail 0
ℹ skipped 1
ℹ todo 1

To run only some cases while debugging, filter by name instead of editing the data:

$ node --test --test-name-pattern="emoji"
✔ case "emoji 🎉 party" (0.8039ms)
ℹ tests 1
ℹ pass 1

This is another reason to put the input in the test name.

Subtests with t.test

Instead of top-level tests you can generate subtests inside one parent test. Use await t.test(...), so the subtests run in order and the parent waits for them:

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { slugify } from '../src/slugify.js';
import fixtures from './fixtures/slugs.json' with { type: 'json' };

test('slugify fixtures', async (t) => {
  for (const { input, expected } of fixtures) {
    await t.test(input, () => {
      assert.equal(slugify(input), expected);
    });
  }
});
▶ slugify fixtures
  ✔ Hello World (0.555ms)
  ✔ Ünïcödé (0.1314ms)
  ✔ 100% pure (0.0698ms)
✔ slugify fixtures (1.5373ms)

Subtests are useful when cases need shared setup that should happen once, inside the parent (for example opening a database connection). For plain tables, describe + test reads better.

Loading cases from files

When there are many cases, or the same cases are shared with another implementation (e.g. a Go or Python port of the same algorithm), keep them in a JSON file:

[
  { "input": "Hello World", "expected": "hello-world" },
  { "input": "Ünïcödé", "expected": "unicode" },
  { "input": "100% pure", "expected": "100-pure" }
]

The example above imports it with an import attribute (with { type: 'json' }), supported without flags in current Node.js. For other formats, or a directory of fixture files, read them yourself. In an ES module you can use top-level await, which runs before the tests are registered:

import { test } from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { slugify } from '../src/slugify.js';

const dir = new URL('./fixtures/', import.meta.url);
const cases = JSON.parse(await readFile(new URL('slugs.json', dir), 'utf8'));

for (const { input, expected } of cases) {
  test(`fixture ${JSON.stringify(input)}`, () => {
    assert.equal(slugify(input), expected);
  });
}

Tests must be registered while the file is loading. Calling test() later, from inside a setTimeout or after an un-awaited promise, doesn't work reliably. Top-level await is fine because module evaluation waits for it. In CommonJS there is no top-level await, so use readFileSync or require('./fixtures/slugs.json').

Combinations of parameters

Nested loops give you every combination. Here every compression codec is tested against every payload:

import { describe, test } from 'node:test';
import assert from 'node:assert/strict';
import {
  gzipSync, gunzipSync,
  deflateSync, inflateSync,
  brotliCompressSync, brotliDecompressSync,
} from 'node:zlib';

const codecs = {
  gzip: [gzipSync, gunzipSync],
  deflate: [deflateSync, inflateSync],
  brotli: [brotliCompressSync, brotliDecompressSync],
};
const payloads = {
  empty: Buffer.alloc(0),
  text: Buffer.from('hello '.repeat(100)),
  binary: Buffer.from([0, 255, 1, 254, 2, 253]),
};

for (const [codec, [compress, decompress]] of Object.entries(codecs)) {
  describe(codec, () => {
    for (const [kind, data] of Object.entries(payloads)) {
      test(`round-trips ${kind} (${data.length} bytes)`, () => {
        assert.deepEqual(decompress(compress(data)), data);
      });
    }
  });
}
▶ gzip
  ✔ round-trips empty (0 bytes) (1.2333ms)
  ✔ round-trips text (600 bytes) (0.2446ms)
  ✔ round-trips binary (6 bytes) (0.2542ms)
✔ gzip (2.4147ms)
▶ deflate
  ✔ round-trips empty (0 bytes) (0.3141ms)
  ✔ round-trips text (600 bytes) (0.2408ms)
  ✔ round-trips binary (6 bytes) (0.218ms)
✔ deflate (0.9379ms)
▶ brotli
  ✔ round-trips empty (0 bytes) (0.8815ms)
  ✔ round-trips text (600 bytes) (0.6472ms)
  ✔ round-trips binary (6 bytes) (0.5565ms)
✔ brotli (2.2741ms)
ℹ tests 9
ℹ suites 3

Using objects keyed by name (Object.entries) gives readable test names for free, which matters when values are functions or buffers that don't print well. The number of tests grows multiplicatively, so keep each dimension small.

Pitfall: var in the loop

Test callbacks run after the loop has finished. With let/const each iteration gets its own binding, but var is shared by all iterations:

describe('var pitfall', () => {
  const inputs = ['a', 'b', 'c'];
  for (var i = 0; i < inputs.length; i++) {
    test(`input #${i}`, () => {
      assert.equal(typeof inputs[i], 'string');
    });
  }
});
▶ var pitfall
  ✖ input #0 (0.8335ms)
  ✖ input #1 (0.1278ms)
  ✖ input #2 (0.1053ms)

The names are correct (they're built during the loop), but every callback sees i === 3 and inputs[3] is undefined. Use for...of with const, or forEach.

Mocha

Mocha registers tests the same way, so a loop or forEach works:

// test/duration.spec.js
import assert from 'node:assert/strict';
import { parseDuration } from '../src/duration.js';

describe('parseDuration', function () {
  const cases = [
    { input: '250ms', expected: 250 },
    { input: '2s', expected: 2000 },
    { input: '1.5m', expected: 90000 },
    { input: '1h', expected: 3600000 },
  ];

  cases.forEach(({ input, expected }) => {
    it(`parses ${input} as ${expected}`, function () {
      assert.equal(parseDuration(input), expected);
    });
  });

  ['', '10', '5 days'].forEach((input) => {
    it(`throws for ${JSON.stringify(input)}`, function () {
      assert.throws(() => parseDuration(input), SyntaxError);
    });
  });
});
$ npx mocha
  parseDuration
    ✔ parses 250ms as 250
    ✔ parses 2s as 2000
    ✔ parses 1.5m as 90000
    ✔ parses 1h as 3600000
    ✔ throws for ""
    ✔ throws for "10"
    ✔ throws for "5 days"

  7 passing (2ms)

Mocha's --grep "1.5m" filters cases by name, like --test-name-pattern.

Vitest and Jest: test.each

Vitest and Jest have dedicated helpers. The API below is from Vitest; Jest's test.each and describe.each work the same way (Jest has no test.for).

// test/duration.test.js
import { describe, test, expect } from 'vitest';
import { parseDuration } from '../src/duration.js';

describe('parseDuration', () => {
  // arrays: spread as arguments, printf-style placeholders in the name
  test.each([
    ['250ms', 250],
    ['2s', 2000],
    ['1.5m', 90000],
  ])('parseDuration(%s) -> %i', (input, expected) => {
    expect(parseDuration(input)).toBe(expected);
  });

  // objects: $name placeholders
  test.each([
    { input: '1h', expected: 3600000 },
    { input: '0.5s', expected: 500 },
  ])('parses $input as $expected', ({ input, expected }) => {
    expect(parseDuration(input)).toBe(expected);
  });

  // tagged template table
  test.each`
    input       | expected
    ${'10ms'}   | ${10}
    ${'3m'}     | ${180000}
  `('table: $input -> $expected', ({ input, expected }) => {
    expect(parseDuration(input)).toBe(expected);
  });

  // test.for: the case is NOT spread; 2nd argument is the test context
  test.for([
    ['', 'empty'],
    ['5 days', 'words'],
  ])('rejects %s (%s)', ([input]) => {
    expect(() => parseDuration(input)).toThrow(SyntaxError);
  });
});

describe.each([
  { unit: 's', factor: 1000 },
  { unit: 'm', factor: 60000 },
])('unit $unit', ({ unit, factor }) => {
  test.each([1, 2, 10])(`%i${unit}`, (n) => {
    expect(parseDuration(`${n}${unit}`)).toBe(n * factor);
  });
});
$ npx vitest run --reporter=verbose
 ✓ test/duration.test.js > parseDuration > parseDuration(250ms) -> 250 1ms
 ✓ test/duration.test.js > parseDuration > parseDuration(2s) -> 2000 0ms
 ✓ test/duration.test.js > parseDuration > parseDuration(1.5m) -> 90000 0ms
 ✓ test/duration.test.js > parseDuration > parses 1h as 3600000 0ms
 ✓ test/duration.test.js > parseDuration > parses 0.5s as 500 0ms
 ✓ test/duration.test.js > parseDuration > table: 10ms -> 10 0ms
 ✓ test/duration.test.js > parseDuration > table: 3m -> 180000 0ms
 ✓ test/duration.test.js > parseDuration > rejects  (empty) 0ms
 ✓ test/duration.test.js > parseDuration > rejects 5 days (words) 0ms
 ✓ test/duration.test.js > unit s > 1s 0ms
 ✓ test/duration.test.js > unit s > 2s 0ms
 ✓ test/duration.test.js > unit s > 10s 0ms
 ✓ test/duration.test.js > unit m > 1m 0ms
 ✓ test/duration.test.js > unit m > 2m 0ms
 ✓ test/duration.test.js > unit m > 10m 0ms

      Tests  15 passed (15)

Common placeholders: %s string, %i integer, %d number, %j JSON, %o object, %# case index, %% literal percent. With object cases, $input or $user.name reads a property. Note how %s printed the empty string as nothing (rejects (empty)); add a label column or use %j when such values matter.

test.for is the better choice when you need the test context (for example ({ expect }) in concurrent tests), and because arrays are not spread, the callback signature doesn't depend on the case shape.

A plain for loop works in Vitest and Jest too. test.each is just a convenience for naming.

Tips

For replacing dependencies inside the tested code, see Mocks and test doubles. To check that your tables actually reach every branch, see Code coverage.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents