Skip to content

Parameterized Test

In one line

A parameterized test runs one test logic against many input/output pairs, reducing duplication. Jest uses test.each().

In simple words

Parameterized tests (also called data-driven or table-driven tests) let you write one test that runs against many different inputs and expected outputs.

Instead of writing 10 separate tests that all do the same thing with different values:

test('add 1+1=2', () => expect(add(1,1)).toBe(2));
test('add 2+2=4', () => expect(add(2,2)).toBe(4));
test('add 3+3=6', () => expect(add(3,3)).toBe(6));

You write one parameterized test:

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

This is DRY, easy to extend (just add a row), and keeps the test logic in one place. If the logic has a bug, you fix it once, not in 10 places.

Example

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

One test definition runs 4 times with different inputs.

Related terms

Related Resources

Related Lessons

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors

← Back to glossary