遍历数组和 运行 每个元素的 Jest 测试不起作用

Looping through an array and run a Jest test for each element does not work

我有一个非常大的 JSON 对象数组。我需要对每个单独的元素进行 运行 Jest 测试。 我尝试先遍历数组,然后在循环中编写测试,如下所示:

describe("Tests", (f) => {
  it("has all fields and they are valid", () => {
    expect(f.portions! >= 0).toBeTruthy();
    expect(f.name.length > 0 && typeof f.name === "string").toBeTruthy();
  });

  it("has an image", () => {
    expect(f.image).toBeTruthy();
  });
});

然而,对于这段代码,Jest 会抱怨“您的测试套件必须至少包含一个测试。”

我是否必须为每个测试循环遍历此数组?

Jest 确实有 describe.eachtest.eachit.each 方法来满足您的需要。它允许您使用不同的 input/output.

进行相同的测试

https://jestjs.io/docs/api#describeeachtablename-fn-timeout

例子:

全局 describe.each :

const params = [
  [true, false, false],
  [true, true, true],
  [false, true, false],
  [false, false, true],
];

describe.each(params)('With params %s, %s, %s', (a, b, c) => {
  it(`${a} === ${b} should be ${c}`, () => {
    expect(a === b).toBe(c);
  });
});

输出:

 PASS  test/integration-tests/test.spec.ts (5.938s)
  With params true, false, false
    √ true === false should be false (2ms)
  With params true, true, true
    √ true === true should be true
  With params false, true, false
    √ false === true should be false (1ms)
  With params false, false, true
    √ false === false should be true

或者使用简单的 it.each :

const params = [
  [true, false, false],
  [true, true, true],
  [false, true, false],
  [false, false, true],
];

describe('Dumb test', () => {
  it.each(params)('%s === %s should be %s', (a, b, c) => {
    expect(a === b).toBe(c);
  });
});

输出:

 PASS  test/integration-tests/test.spec.ts
  Dumb test
    √ true === false should be false (2ms)
    √ true === true should be true
    √ false === true should be false
    √ false === false should be true