【问题标题】:How are async tests executed in JestJest 中如何执行异步测试
【发布时间】:2023-04-06 23:01:01
【问题描述】:

我正在尝试使用 Jest 进行测试。我想了解 JEST 在以下场景中的行为:

  1. 当异步函数通过测试时
  2. 当包含异步代码的同步函数传递给测试时。

请查看下面的 sippet 以供参考。

我想知道测试在这两种情况下是否异步执行。

it('should do async stuff...', async () => {
    const result = await doSomething();
    expect(result).toBe('value');
})

it('should do async stuff...', () => {
    async () => {
        const result = await doSomething();
        expect(result).toBe('value');

    }();
})

提前致谢

【问题讨论】:

    标签: javascript node.js typescript jestjs


    【解决方案1】:

    由于第二个测试的函数没有声明为async,它将同步运行。自调用函数将被执行,但 Jest 会在任何事情发生之前关闭执行范围。

    您可以使用以下扩展您的 sn-p 的代码自己清楚地看到它:

    async function doSomething(ms) {
      return new Promise((resolve) =>
        setTimeout(() => {
          resolve("value");
        }, ms)
      );
    }
    
    describe("compare async tests", () => {
      it("test 1", async () => {
        const result = await doSomething(2000);
        console.log("test 1", { result });
        expect(result).toBe("value");
      });
    
      it("test 2", () => {
        (async () => {
          const result = await doSomething(1000);
          console.log("test 2", { result });
          expect(result).toBe("value");
        })();
      });
    });
    

    运行上述命令会将两个测试都标记为成功,但您只会在控制台输出中看到“测试 1”。

    【讨论】:

      猜你喜欢
      • 2022-11-09
      • 1970-01-01
      • 1970-01-01
      • 2018-03-24
      • 2017-04-18
      • 2020-03-15
      • 1970-01-01
      • 2021-07-07
      • 2021-01-29
      相关资源
      最近更新 更多