如何使用Jest beforeAll来加载测试用例?

v9tzhpje  于 2023-05-21  发布在  Jest
关注(0)|答案(2)|浏览(225)

我试图在测试运行之前从外部源加载示例用例。以下操作失败,错误为``.each must be called with an Array or Tagged Template Literal. Instead was called with: undefined。为什么beforeAll在测试之前不执行?

let samples: string[];

beforeAll(() => {
  samples = ["first sample foo", "second foo sample"];
});

describe(`Test Samples`, () => {
  test.each(samples)("should include foo", (sample) => {
    // NEVER GETS HERE
    expect(sample.includes("foo")).toBe(true);
  });
});

您可能会问为什么不加载describe之前的样本。我从异步源加载示例,describe不支持async修饰符。

6kkfgxo0

6kkfgxo01#

故障排除#定义测试
测试必须同步定义,Jest才能收集测试。
这意味着当您使用test.each时,不能在beforeEach/beforeAll中异步设置表

let samples: string[] = ["first sample foo", "second foo sample"];

// beforeAll(() => {
// samples = ["first sample foo", "second foo sample"];
// });

describe(`Test Samples`, () => {
  test.each(samples)("should include foo", (sample) => {
    expect(sample.includes("foo")).toBe(true);
  });
});

测试结果:

PASS  stackoverflow/76282171/index.test.ts (13.983 s)
  Test Samples
    ✓ should include foo (19 ms)
    ✓ should include foo (2 ms)

  console.log
    sample:  first sample foo

      at stackoverflow/76282171/index.test.ts:10:13

  console.log
    sample:  second foo sample

      at stackoverflow/76282171/index.test.ts:10:13

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        15.106 s
kadbb459

kadbb4592#

post可以帮助您。
简而言之,问题是在beforeAll中获取数据没有帮助,因为测试是在实际运行之前定义的。因此,beforeAll将在定义测试之后运行。这意味着注册测试时samples数组为空。

相关问题