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

2skhul33  于 2023-02-14  发布在  Jest
关注(0)|答案(1)|浏览(168)

我有一个非常大的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抱怨“您的测试套件必须至少包含一个测试”。
我是否必须为每个测试循环遍历这个数组?

lx0bsm1f

lx0bsm1f1#

Jest确实有describe.eachtest.eachit.each方法来满足你的需要,它允许你用不同的输入/输出做同样的测试。
https://jestjs.io/docs/api#describeeachtablename-fn-timeout

    • 示例:**

使用全局描述。每个:

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

相关问题