【问题标题】:How to use jest.each asynchronously如何异步使用 jest.each
【发布时间】:2020-05-28 02:08:55
【问题描述】:

我在将文件名异步加载到 jest.each 时遇到问题。

我的代码:

let files: string[][]

function getFilesWorking() {
  files = [["test1"], ["test2"]]
}

async function getFilesAsync() {
  files = await Promise.resolve([["test1"], ["test2"]])
}

beforeAll(() => {
  console.log("before")
})

describe.only("Name of the group", () => {
  getFilesAsync()
  test.each(files)("runs", f => {})
})

beforeAll 在每次测试之前执行,但不是在 test.each 初始化之前执行,所以我最终得到 undefined。

如何在使用 test.each 之前加载文件?

【问题讨论】:

  • 你需要await你的getFilesAsync()电话
  • 我无法将异步函数作为 cb 传递来描述,所以我无法等待

标签: node.js async-await jestjs


【解决方案1】:

您可以将async 回调传递给其中的beforeAllawait getFilesAsync

beforeAll(async () => {
  await getFilesAsync();
})

【讨论】:

  • @mspoulsen 是的,抱歉,我误解了这个问题。所有的测试定义都必须使用静态数据
  • 是的...我意识到了这一点。谢谢;)
【解决方案2】:

您可以使用beforeEach 设置将在任何给定范围https://jestjs.io/docs/setup-teardown 的测试之前运行的代码:

beforeEach(() => {
    console.log('before every test');
});

describe.only(('Name of the group') => {
    beforeEach(() => {
        console.log('before tests in this describe block');
    })
})

Jest 只会在您的 describe.only 块中运行测试。如果您想在其他块中使用beforeEach 并同时运行这些测试,请将describe.only 更改为describe

(编辑:我知道这已经晚了一年,我只是想寻找类似的问题/解决方案集,并认为我可以回答这个问题。)

【讨论】:

    猜你喜欢
    • 2020-06-14
    • 2012-01-20
    • 2017-09-03
    • 2020-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-10
    相关资源
    最近更新 更多