【问题标题】:jest test async function fail开玩笑测试异步功能失败
【发布时间】:2020-10-08 10:32:51
【问题描述】:

我有一个简单的打字稿功能,它只打印一些文本和睡眠。测试完成,无需等待异步函数返回。

这是我的功能。

test('sleep test', () => {
    function sleep(ms: number) {
        return new Promise((resolve) => setTimeout(resolve, ms));
    }

    async function delayedGreeting() {
        console.log('Hello');
        await sleep(5000);
        console.log('World!');
        await sleep(5000);
        console.log('Goodbye!');
    }

    delayedGreeting();
});

测试以控制台中的“Hello”结束。

我尝试了本网站https://www.sitepoint.com/delay-sleep-pause-wait/ 建议的其他形式。我的测试总是以仅打印“Hello”结束。

项目的骨架是从带有 typescript 选项的 create-react-app 生成的。 我的项目中有这些依赖项。

  "dependencies": {
    "@types/node": "^12.12.47",
    "@types/react": "^16.9.38",
    "@types/react-dom": "^16.9.8",
    "@types/zeromq": "^4.6.3",
    "protobuf-typescript": "^6.8.8",
    "react": "^16.13.1",
    "react-dom": "^16.13.1",
    "react-scripts": "3.4.1",
    "typescript": "^3.7.5",
    "zeromq": "^6.0.0-beta.6"
  },
  "devDependencies": {
    "@testing-library/jest-dom": "^4.2.4",
    "@testing-library/react": "^9.5.0",
    "@testing-library/user-event": "^7.2.1",
    "@types/jest": "^24.9.1",
    "@typescript-eslint/eslint-plugin": "^3.3.0",
    "@typescript-eslint/parser": "^3.3.0",
    "eslint-config-prettier": "^6.11.0",
    "eslint-plugin-prettier": "^3.1.4",
    "eslint-plugin-react": "^7.20.0",
    "prettier": "^2.0.5"
  },

我使用npm test 来运行我的测试。

这和 Jest 有关系吗?如何在我的测试中解决这个问题?谢谢。

【问题讨论】:

    标签: typescript async-await jestjs


    【解决方案1】:

    测试不应该等待异步任务,因为它是同步的。 Jest 提前退出,因为它没有什么可等待的,这可以使用detectOpenHandles 选项进行调试。

    Jest supports promises 用于异步测试,应该是:

    test('sleep test', async () => {
        await delayedGreeting();
        ...
    });
    

    【讨论】:

      【解决方案2】:

      您的测试调用delayedGreeting() 打印Hello 然后启动异步操作并返回。 await 语句只有在使用它的函数是 await-ed 本身(等等)时才能按预期工作。

      Jest 没有等待您的异步流程完成,因为没有人告诉它这样做。

      您可以将sleep()delayedGreeting() 函数移到测试之外,以使测试更易于阅读。

      function sleep(ms: number) {
          return new Promise((resolve) => setTimeout(resolve, ms));
      }
      
      async function delayedGreeting() {
          console.log('Hello');
          await sleep(5000);
          console.log('World!');
          await sleep(5000);
          console.log('Goodbye!');
      }
      

      使测试工作的最简单方法是将测试实现函数声明为async,并让它await delayedGreeting()

      test('sleep test', async () => {
          await delayedGreeting();
      });
      

      这样 Jest 知道它必须等待等待 delayedGreeting() 的测试函数,然后等待 sleep() 的两个调用返回的两个 Promises 完成。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-17
        • 2020-03-11
        • 2018-09-25
        • 2018-02-13
        • 2018-02-22
        • 1970-01-01
        • 2017-11-19
        • 1970-01-01
        相关资源
        最近更新 更多