首页 > 解决方案 > 在带有 TypeScript 的 react-testing-library act() 中使用 Jest Fake Timer

问题描述

我将 Jest 与react-testing-library一起使用,并在模拟推进计时器时遇到此警告:

 console.error
      Warning: An update to TimerProvider inside a test was not wrapped in act(...).
      
      When testing, code that causes React state updates should be wrapped into act(...):
      
      act(() => {
        /* fire events that update state */
      });
      /* assert on the output */

经过一番搜索,我发现了一个视频,建议将任何调用包装jest.advanceTimersByTimeact()function中。

act(() => jest.advanceTimesByTime(1000);

但是我正在使用 TypeScript,现在对如何解决产生的类型错误感到困惑:

TS2769:Type 'typeof jest' is not assignable to type 'void'.

如何正确修复此类型错误?

标签: reactjstypescriptjestjsreact-testing-library

解决方案


我遇到了和你一样的问题,用大括号转换为常规函数可以防止类型错误:

act(() => {
  jest.advanceTimersByTime(1000);
});


推荐阅读