You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用@testing-library/react-hooks的act函数触发no-floating-promises lint错误求助

解决react-hooks-testing-library中act的lint错误(@typescript-eslint/no-floating-promises)

首先明确:你完全可以用void运算符来显式忽略这个lint错误,不过更推荐先调整测试写法——这个错误本质是你在同步操作场景下不必要地用了async/await包裹act,属于写法冗余导致的lint告警。

问题根源分析

你的第二个测试用例里,setValue((prev) => prev + 3)是纯同步操作(你的自定义Hook本身并非异步),但你却用了await act(async () => { ... }),还手动返回了Promise.resolve(),这就导致lint认为你在等待一个无意义的Promise,触发了no-floating-promises规则。

正确的测试写法

对于同步的Hook状态更新,直接用普通的act包裹即可,完全不需要async/await:

import { renderHook, act } from '@testing-library/react-hooks'
import useRefWithSetter from '../useRefWithSetter'

describe('Test useRefWithSetter', () => {
  const { result } = renderHook(() => useRefWithSetter(1))
  const [valueRef, setValue] = result.current

  test('you can return value through setter function', () => {
    act(() => {
      setValue(2)
    })
    expect(valueRef.current).toBe(2)
  })

  test('you can return callback function through setter function', () => {
    // 同步操作无需async/await,直接用act包裹即可
    act(() => {
      setValue((prev) => prev + 3)
    })
    expect(valueRef.current).toBe(5)
  })
})

什么时候需要await act?

只有当你的Hook内部包含异步操作(比如setTimeout、API请求、Promise回调)时,才需要用async/await配合act,示例如下:

test('handles async updates in hook', async () => {
  await act(async () => {
    // 调用Hook内部的异步方法
    await result.current.triggerAsyncUpdate()
  })
  // 断言异步更新后的状态
  expect(result.current.someState).toBe('updated')
})

用void忽略错误的场景

如果你因为某些原因必须保留async包裹(比如测试逻辑后续计划添加异步操作),可以用void显式告知lint忽略这个Promise:

test('you can return callback function through setter function', () => {
  void act(async () => {
    setValue((prev) => prev + 3)
  })
  expect(valueRef.current).toBe(5)
})

不过这种写法属于“掩盖”告警,不如直接调整为同步act写法更规范。

内容的提问来源于stack exchange,提问作者Jiyeol Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:18:45