Jest 的 test.each 是参数化测试语法糖,支持数组+模板字符串(%i占位符)和对象数组+解构($key引用)两种写法,并可搭配 describe.each 分组组织测试,需注意参数匹配、异步处理及并行执行等细节。

Jest 的 test.each 是专门用于参数化测试的语法糖,能用一组数据驱动多个相同逻辑的测试用例,避免重复写 test,大幅提升可维护性和覆盖率。
基础写法:数组 + 模板字符串
最常用的是传入二维数组,每项是一组参数,配合带占位符的模板字符串描述用例:
test.each([
[1, 2, 3],
[0, 0, 0],
[-1, 1, 0],
])('add(%i, %i) returns %i', (a, b, expected) => {
expect(a + b).toBe(expected);
});说明:
- %i 是 Jest 内置占位符(%s 字符串、%j JSON),自动格式化对应参数;
- 每个子数组对应一次执行,Jest 会生成独立测试名,失败时精准定位哪组数据出错。
进阶写法:对象数组 + 解构
当参数多或语义复杂时,用对象数组更清晰:
test.each([
{ input: 'hello', output: 'HELLO' },
{ input: 'WORLD', output: 'WORLD' },
{ input: ' js ', output: 'JS' },
])('toUpperCase($input) → $output', ({ input, output }) => {
expect(input.trim().toUpperCase()).toBe(output);
});说明:
- 模板中用 $key 引用对象属性,支持嵌套(如 $user.name);
- 解构参数让断言逻辑更易读,适合校验函数行为、API 响应结构等场景。
搭配 describe.each 实现分层组织
若需对同一函数在不同场景下批量测试(比如边界值、异常输入),可用 describe.each 分组:
describe.each([
['positive', [1, 2, 3]],
['negative', [-1, -2, -3]],
['mixed', [1, -1, 0]],
])('sum %s numbers', (_, numbers) => {
test('returns correct total', () => {
expect(numbers.reduce((a, b) => a + b, 0)).toBe(
numbers.length > 0 ? numbers.reduce((a, b) => a + b, 0) : 0
);
});
<p>test('handles empty array', () => {
expect([].reduce((a, b) => a + b, 0)).toBe(0);
});
});说明:
- 第一个参数是描述性标签(如 'positive'),第二个是实际数据;
- 每组 describe 下可包含多个 test,共享上下文又保持数据隔离。
注意事项与技巧
注意这些细节,避免踩坑:
- 数组项数量必须和参数个数严格匹配,否则运行时报错;
- 异步测试中,确保
async/await或返回 Promise,Jest 才会等待; - 想跳过某组数据?用
test.skip.each或在数据中加标记字段 + 条件判断; - 数据量大时,考虑用
it.concurrent.each并行执行(但注意副作用和状态污染)。


















