【问题标题】:Where do I run asynchronous code required for test setup in Jest?我在哪里运行 Jest 中测试设置所需的异步代码?
【发布时间】:2020-10-21 02:58:14
【问题描述】:

我想在 Jest 中的 for 循环内动态运行多个测试,但我不确定在哪里放置我的测试环境所需的异步代码。

一个可行的选择是将所有异步代码放在一个测试函数中,并为 for 循环的每次迭代执行一个断言语句。

 describe('Database Testing', () => {

   test(`Testing ${items}`, async () => {

     const items = await getItems(); //<-- asynchronous code

     for (const item of items) {

        expect('hi').toEqual('hi');
     }
   });
 });

但是,如果测试失败,我将无法确定 assert 语句在哪个循环中失败。相反,我想要一个类似于下面的结构,在该结构中,我为 for 循环的每次迭代动态运行测试。

 describe('Database Testing', () => {

   const items = await getItems(); //<-- asynchronous code

   for (const item of items) {

      test(`Testing ${item}`, async () => {
         expect('hi').toEqual('hi');
       });
    };
 });

由于 describe 函数的同步性质,我无法运行异步代码。但是,如果我在 describe 函数中使用 async 关键字,则会收到错误消息“不支持从“describe”返回 Promise”。

我应该在哪里运行异步代码?

【问题讨论】:

    标签: javascript asynchronous testing jestjs


    【解决方案1】:

    beforeAll 可以是异步的。您还可以在 describe 中使用异步的 it 函数。

    这是关于测试异步的笑话文档:https://jestjs.io/docs/en/tutorial-async

    beforeAll(async () => {
    // do async things
    })
    
    describe('whatever', () => {
      it('will do something async', async () => {
        expect.assertions(1);
        // do something async
        //... expect something
      })
    })
    

    只需确保您的expect.assertions 与适当数量的assertions 匹配即可。

    【讨论】:

    • 我实际上喜欢将beforeAll 放在describe 中,这样我就可以在同一个文件中进行多个设置。但是,是的,这会工作
    • @blex 从未想过这一点。我什至不知道这会起作用。从现在开始,这实际上会让我的安全带变得更容易。谢谢!
    【解决方案2】:

    会有这样的工作:

     describe('Database Testing', () => {
       getItems().then(items -> {
            for (const item of items) {
               expect('hi').toEqual('hi');
            };
         });
     });
    

    【讨论】:

      猜你喜欢
      • 2018-04-30
      • 2019-08-23
      • 2017-09-20
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-12
      • 2019-03-07
      • 2020-03-01
      相关资源
      最近更新 更多