循环遍历数组并对每个元素运行 Jest 测试不起作用

Sim*_*eta 0 javascript testing node.js jestjs ts-jest

我有一个非常大的 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();
  });
});
Run Code Online (Sandbox Code Playgroud)

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

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

Rob*_*hay 6

Jest 确实有describe.eachtest.eachit.each满足您需求的方法。它允许您使用不同的输入/输出进行相同的测试。

\n

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

\n

例子 :

\n

使用全局描述.each:

\n
const params = [\n  [true, false, false],\n  [true, true, true],\n  [false, true, false],\n  [false, false, true],\n];\n\ndescribe.each(params)(\'With params %s, %s, %s\', (a, b, c) => {\n  it(`${a} === ${b} should be ${c}`, () => {\n    expect(a === b).toBe(c);\n  });\n});\n
Run Code Online (Sandbox Code Playgroud)\n

输出 :

\n
 PASS  test/integration-tests/test.spec.ts (5.938s)\n  With params true, false, false\n    \xe2\x88\x9a true === false should be false (2ms)\n  With params true, true, true\n    \xe2\x88\x9a true === true should be true\n  With params false, true, false\n    \xe2\x88\x9a false === true should be false (1ms)\n  With params false, false, true\n    \xe2\x88\x9a false === false should be true\n
Run Code Online (Sandbox Code Playgroud)\n

或者使用简单的 it.each :

\n
 PASS  test/integration-tests/test.spec.ts (5.938s)\n  With params true, false, false\n    \xe2\x88\x9a true === false should be false (2ms)\n  With params true, true, true\n    \xe2\x88\x9a true === true should be true\n  With params false, true, false\n    \xe2\x88\x9a false === true should be false (1ms)\n  With params false, false, true\n    \xe2\x88\x9a false === false should be true\n
Run Code Online (Sandbox Code Playgroud)\n

输出 :

\n
 PASS  test/integration-tests/test.spec.ts\n  Dumb test\n    \xe2\x88\x9a true === false should be false (2ms)\n    \xe2\x88\x9a true === true should be true\n    \xe2\x88\x9a false === true should be false\n    \xe2\x88\x9a false === false should be true\n
Run Code Online (Sandbox Code Playgroud)\n