Parameterized Tests
Have you ever written the same test ten times with different inputs? Yeah, that gets old fast. Parameterized tests let you run the same test logic with different data. It is like a loop for your tests.
Here is the thing. Instead of writing ten separate test blocks, you write one test and give it a table of inputs and expected outputs.
Using test.each
Jest has a built-in test.each function. You pass it an array of arrays, and each inner array becomes a test case.
const sum = (a, b) => a + b;
test.each([
[1, 2, 3],
[0, 0, 0],
[-1, -2, -3],
[10, 20, 30]
])('adds %i and %i to get %i', (a, b, expected) => {
expect(sum(a, b)).toBe(expected);
});
That one test block runs four times with different values. Each run gets its own clear output showing the inputs.
Using describe.each
You can also parameterize entire describe blocks. This is useful when you need different setup for each case.
describe.each([
{ input: 5, expected: 25, label: 'positive number' },
{ input: 0, expected: 0, label: 'zero' },
{ input: -3, expected: 9, label: 'negative number' }
])('square of $label', ({ input, expected }) => {
it(`returns ${expected}`, () => {
expect(square(input)).toBe(expected);
});
});
Inline Snapshot with Parameterized Tests
When you combine parameterized tests with snapshots, you can quickly build a comprehensive test suite.
test.each([
['hello', 'HELLO'],
['world', 'WORLD'],
['jest', 'JEST']
])('uppercase of %s is %s', (input, expected) => {
expect(input.toUpperCase()).toBe(expected);
});
When to Use Parameterized Tests
Use them when you have the same logic with different inputs. Great for validation functions, calculations, and data transformations. If each test case needs completely different setup, separate tests might be clearer.
Try it Yourself →Key Takeaways
- test.each runs the same test with different inputs
- describe.each parameterizes entire describe blocks
- Use them to reduce duplication in similar test cases
- Great for validation, calculations, and data transformations
- Keep the data format simple and readable