写Jest时必须setTimeout的情况

无法使用jest.useFakeTimers的情况: setTimeout中出现了ref.current,且使用这个ref的组件还未渲染

具体的业务场景是写了一个按钮,在点击之后Modal弹窗会显示,500ms后弹窗中的输入框会获得焦点

ts 复制代码
onClick={() => {
  open();
  setTimeout(() => {
    ref.current.focus();
  }, 500);
}}

如上代码所示,当你打算在setTimeout中访问ref.current时,且如果使用了如下代码

js 复制代码
// 指定 Jest 使用假的全局日期、性能、时间和定时器 API
beforeEach(() => {
  jest.useFakeTimers()
});
afterEach(() => {
  jest.runOnlyPendingTimers()
  jest.useRealTimers()
});

user.click(button)就会超时,此时,如果你使用waitFor将其包裹,则会看到真正的报错

js 复制代码
await waitFor(() => user.click(button));
javascript 复制代码
    TypeError: Cannot read properties of null (reading 'focus')

  36 |         setTimeout(() => {
> 37 |           ref.current.focus();
     |                       ^
  38 |         }, 500);
  39 |       }}

根因是因为jest.useFakeTimers运行了之后,setTimeout会立即执行,不会等待,而这时的ref.current还未被赋值。

React提供的act函数可以在包裹一段代码后,可以等待react组件渲染完成。

一般我们可以把它包在render函数之外,如下代码所示:

js 复制代码
it ('renders with button disabled', async () => {
  await act(async () => {
    root.render(<TestComponent />)
  });
  expect(container.querySelector('button')).toBeDisabled();
});

这样即使TestComponent中使用了useRef,对应的ref也能获取到值。

但由于我们测试的是modal组件,需要点击之后才显示,所以无法使用这个方案。

所以解决方案就是,删除jest.useFakeTimers相关代码,让setTimeout异步执行,这样ref才能在click后有时间获取到值。由于此时需要等待500ms,所以我们也需要setTimeout,由于此时react组件会更新,所以我们需要用act包裹,所以最终的解决方案就是

tsx 复制代码
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
it('点击按钮后,出现弹窗且输入框获得焦点', async () => {
  const user = userEvent.setup();
  render(
    <Modal>
      <Button>创建</Button>
    </Modal>
  );
  const button = screen.getByText('创建');
  await user.click(button);
  await act(async () => await sleep(500)); // 等待ref获得值并focus
  expect(screen.getByPlaceholderText('请输入')).toHaveFocus();
});
相关推荐
AAA阿giao3 小时前
从零构建一个现代登录页:深入解析 Tailwind CSS + Vite + Lucide React 的完整技术栈
前端·css·react.js
昨晚我输给了一辆AE865 小时前
为什么现在不推荐使用 React.FC 了?
前端·react.js·typescript
不会敲代码15 小时前
深入浅出 React 闭包陷阱:从现象到原理
前端·react.js
不会敲代码15 小时前
React性能优化:深入理解useMemo和useCallback
前端·javascript·react.js
不会敲代码112 小时前
从入门到进阶:手写React自定义Hooks,让你的组件更简洁
前端·react.js
pe7er1 天前
状态提升:前端开发中的状态管理的设计思想
前端·vue.js·react.js
晚风予星1 天前
Ant Design Token Lens 迎来了全面升级!支持在 .tsx 或 .ts 文件中直接使用 Design Token
前端·react.js·visual studio code
青青家的小灰灰1 天前
React 架构进阶:自定义 Hooks 的高级设计模式与最佳实践
前端·react.js·前端框架
yuki_uix2 天前
Props、Context、EventBus、状态管理:组件通信方案选择指南
前端·javascript·react.js
牛奶2 天前
React 底层原理 & 新特性
前端·react.js·面试