测试 React:“不要等待使用同步逻辑调用 act(...) 的结果”

Jul*_*anG 7 javascript testing warnings reactjs react-hooks

使用 react 和 react-dom 16.9.0

我在测试 React 钩子时收到此警告:

console.error node_modules/react-dom/cjs/react-dom-test-utils.development.js:80
Warning: Do not await the result of calling act(...) with sync logic, it is not a Promise.
Run Code Online (Sandbox Code Playgroud)

我的测试代码(在@testing-library/react 中使用 jest)

...
await act( () => {
  rerender(
    <HookTester
      promise={asyncFunction}
      initialValue={'extra loading...'}
    />
  );
});

expect(asyncFunction).toHaveBeenCalledTimes(2);
...
Run Code Online (Sandbox Code Playgroud)

但如果我不等待,那么我的expectation 就太早了。

Jul*_*anG 17

哦!我知道了!

事实证明,文档提到了这样的同步函数:

act( () => {
  // ... some 'sync logic'
});
Run Code Online (Sandbox Code Playgroud)

你不能等待。

但是你当然可以等待一个异步函数:

await act( async () => {
  // ... some 'async logic'
});
Run Code Online (Sandbox Code Playgroud)

这为我解决了问题。

  • 一瞬间,我很兴奋,因为文档可能实际上已经更新为包含“异步行为”语法,但遗憾的是,官方文档中仍然没有关于这个重要功能的信息。 (6认同)
  • 是的.... async wait 就和你能得到的一样简单。不明白投诉 (3认同)
  • 这就是我不喜欢 RTL 的地方。所有的 async 和 await 都使得测试代码过于冗长,然后你必须定义 var 来保存行为之外的渲染结果,这样你也可以在行为之外断言,就像你应该的那样 (2认同)