简体   繁体   English

Jest 中如何执行异步测试

[英]How are async tests executed in Jest

I am trying to perform testing using Jest.我正在尝试使用 Jest 进行测试。 I would like to understand the behaviour of JEST in the following scenarios:我想了解 JEST 在以下情况下的行为:

  1. When an async function passed to the test当异步 function 通过测试时
  2. When a synchronous function containing an async code passed to a test.当包含异步代码的同步 function 传递给测试时。

Please check the below sippet for reference.请检查下面的 sippet 以供参考。

I would like to know whether the tests execute asynchronously in both the scenarios.我想知道测试是否在这两种情况下都异步执行。

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');

    }();
})

Thanks in advance提前致谢

Since the function of the second test is not declared as async , it will run synchronously .由于第二个测试的 function 没有声明为async ,它将同步运行。 The self-calling function will be executed but Jest will close the execution scope before anything can happen.自调用 function 将被执行,但 Jest 将在任何事情发生之前关闭执行 scope。

You can clearly see it by yourself with the following code which extends your snippet:您可以使用以下扩展代码段的代码自己清楚地看到它:

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");
    })();
  });
});

Running the above will mark both test as successful but you'll only see "test 1" in the console output.运行上述代码会将两个测试都标记为成功,但您只会在控制台 output 中看到“测试 1”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM