Jest provides methods for parameterized testing using test.each or describe.each to run multiple test data sets:
1. Using test.each for Parameterized Testing:
javascripttest.each([ [1, 1, 2], [1, 2, 3], [2, 1, 3], ])('adds %i + %i = %i', (a, b, expected) => { expect(add(a, b)).toBe(expected); });
2. Using Object Arrays:
javascripttest.each([ { a: 1, b: 1, expected: 2 }, { a: 1, b: 2, expected: 3 }, { a: 2, b: 1, expected: 3 }, ])('$a + $b = $expected', ({ a, b, expected }) => { expect(add(a, b)).toBe(expected); });
3. Using describe.each for Grouped Testing:
javascriptdescribe.each([ ['node', 'node'], ['jsdom', 'browser'], ])('test environment: %s', (env, type) => { test(`runs in ${type} environment`, () => { expect(process.env.NODE_ENV).toBeDefined(); }); });
4. Testing Table Data:
javascripttest.each` a | b | expected ${1} | ${1} | ${2} ${1} | ${2} | ${3} ${2} | ${1} | ${3} `('returns $expected when $a is added to $b', ({ a, b, expected }) => { expect(add(a, b)).toBe(expected); });
5. Testing Edge Cases:
javascripttest.each([ [0, 0, 0], [Number.MAX_SAFE_INTEGER, 1, Number.MAX_SAFE_INTEGER + 1], [Number.MIN_SAFE_INTEGER, -1, Number.MIN_SAFE_INTEGER - 1], ])('handles edge cases: %i + %i = %i', (a, b, expected) => { expect(add(a, b)).toBe(expected); });
6. Testing Error Cases:
javascripttest.each([ [undefined, 'input is required'], [null, 'input is required'], ['', 'input cannot be empty'], ])('throws error for invalid input: %p', (input, expectedError) => { expect(() => validate(input)).toThrow(expectedError); });
Best Practices:
- Use parameterized testing to reduce code duplication
- Clearly describe test data and expected results
- Test normal cases and edge cases
- Use table format for better readability
- Keep test data concise and clear