Jest 提供了参数化测试的方法,可以使用 test.each 或 describe.each 来运行多组测试数据:
1. 使用 test.each 进行参数化测试:
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. 使用对象数组:
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. 使用 describe.each 进行分组测试:
javascriptdescribe.each([ ['node', 'node'], ['jsdom', 'browser'], ])('test environment: %s', (env, type) => { test(`runs in ${type} environment`, () => { expect(process.env.NODE_ENV).toBeDefined(); }); });
4. 测试表格数据:
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. 测试边界情况:
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. 测试错误情况:
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); });
最佳实践:
- 使用参数化测试减少重复代码
- 清晰描述测试数据和预期结果
- 测试正常情况和边界情况
- 使用表格格式提高可读性
- 保持测试数据简洁明了