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

React Testing Library如何测试TextField输入框的字符长度

核心问题定位

你原来的测试偶现失败的根本原因是没有给userEvent.type加await:userEvent v14及以上版本的所有交互方法都是异步API,不加await会导致输入操作还没执行完成就跑后面的断言,才会出现少1个字符的情况。

实现值长度校验的方法

MUI的TextField组件会正确绑定label和原生input元素,你通过findByLabelText拿到的就是原生HTMLInputElement实例,直接访问它的value属性就可以获取当前输入值,再校验长度即可。

修改后的完整测试代码

it('disables save button on newly created step in edit state when input field has more than 100 characters', async () => {
  render(<Component />)
  await waitFor(
    () => {
      expect(screen.getByText('Add')).toBeInTheDocument()
      userEvent.click(screen.getByText('Add'))
    },
    { timeout: 10000 },
  )

  // 给type方法加await,等待输入完成
  await userEvent.type(screen.getByLabelText(/Name/i), 'n'.repeat(101))

  const nameInput = await screen.findByLabelText(/Name/i)
  // 直接校验值长度≥100,不需要匹配完整字符串
  expect(nameInput.value.length).toBeGreaterThanOrEqual(100)
  expect(await screen.findByText('Save')).toBeDisabled()
})

内容的提问来源于stack exchange,提问作者Haq.H

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 13:15:06