Skip to content

Parameterized 测试

运行相同 assertion over 许多输入使用它.每个 and 描述.每个.

你将学到

  • 为什么 parameterized 测试 beat 复制-粘贴测试情况
  • Using 它.每个 and 描述.每个使用数组 and 表
  • Naming parameterized 测试清晰地从 数据
  • Keeping parameterized 测试 readable and debuggable

概念讲解

DRY Your Test Cases

When a function should behave the same way for many inputs, copy-pasting a test for each case bloats the file and hides the pattern. A parameterized test defines the assertion once and feeds it a table of inputs and expected outputs. The runner generates one test case per row, each with its own name and pass/fail status, so you get the coverage of many tests with the maintenance of one.

it.each

In Vitest and Jest, 它.每个(表)(name, fn) creates a test per row. The table can be an array of arrays, an array of objects, or a tagged template literal that reads like a table. The name string can interpolate %$ placeholders so each generated test has a descriptive title showing its inputs. 描述.每个 does the same at the describe level, grouping a whole block of tests per row.

Naming Matters

A parameterized test is only useful if each generated case is identifiable when it fails. Use the name template to include the inputs: 它.每个(情况)("添加(%i, %i) -> %i", (, b, expected) => ...). When case 47 fails, the report should show 添加(2, 3) -> 5 not 情况 47. Good names turn a wall of failures into a readable list of broken scenarios.

Readability and Limits

Parameterized tests shine for pure functions and data transformations. They are less helpful when each case needs different setup or different assertions — forcing those into a table makes the test harder to read than separate tests. If the setup diverges, split into multiple parameterized groups or fall back to individual tests. Always include edge cases (empty, zero, negative, boundary) in the table.

In Practice

When building a parameterized table, include the obvious cases, the boundary values, and the edge cases that have bitten you before — empty arrays, zero, negative numbers, very large inputs, unicode strings. Use the tagged-template form of 它.每个 for readability when the table is wide: it reads like a spreadsheet and reviewers can scan the rows. If a single row fails, the runner reports the row's name, so invest in naming. For async cases, make the test function 异步 and await inside the body — the runner handles each row as its own test. When the table grows past twenty rows, consider whether some rows are testing the same thing with different data and could be consolidated, or whether the function has too many branches and should be simplified.

示例代码

              import { describe, it, expect } from "vitest";

function classify(n: number): "negative" | "zero" | "positive" {
  if (n < 0) return "negative";
  if (n === 0) return "zero";
  return "positive";
}

describe("classify", () => {
  it.each([
    [-5, "negative"],
    [-1, "negative"],
    [0, "zero"],
    [1, "positive"],
    [42, "positive"],
  ])("classify(%i) returns %s", (input, expected) => {
    expect(classify(input)).toBe(expected);
  });
});
            

One assertion, five generated 测试情况. 每个情况's name shows 它的输入 and expected 输出, 所以失败 pinpoints 精确地哪个场景 broke.

动手试一试

  • JSON Formatter

    格式输入表 你 feed 到它.每个.

  • Code Diff

    Compare expected 对比实际 for 每个 parameterized 行.

常见错误

错误写法

Generic names 如 '情况 %i' for parameterized 测试

正确做法

Interpolate 输入到 name 所以 failures 是 self-描述: '添加(%i, %i) -> %i' beats '情况 3'.

错误写法

Forcing divergent setups 到 one parameterized 表

正确做法

如果每个行 需要不同设置, 拆分到 separate 测试 or 分组. 表那个分支 on 行类型是 harder 到读取 than individual 测试.

练习 Parameterized 测试

4 个练习

练习 Parameterized 测试

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误