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

React中使用@testing-library/user-event测试time输入框失败,如何修复?

测试time类型输入框时的问题与解决方法

失败原因

直接使用user.type输入字符串时,time类型输入框的原有值不会被自动覆盖,逐个输入的字符会与原有内容混合。加上time输入框有固定的HH:mm格式约束,光标位置和输入逻辑的差异会导致最终值不符合预期,比如你得到的10:59就是原有值与输入字符错误混合后的结果。

修正后的测试方案

方案1:先清空输入框再输入新值

通过user.clear()模拟用户清空输入框的操作,确保输入新值前输入框为空,再输入目标时间:

import userEvent from '@testing-library/user-event';
import { render, screen } from '@testing-library/react';

it('should update a value of a time input', async () => {
  const user = userEvent.setup();
  render(
    <label>
      Time:
      <input type="time" defaultValue="10:30" />
    </label>
  );
  const input = screen.getByLabelText('Time:');
  await user.clear(input);
  await user.type(input, '06:45');
  expect(input).toHaveValue('06:45');
});

方案2:模拟用户全选后输入新值

先点击输入框,再通过键盘快捷键全选现有内容,最后输入新值,还原用户实际操作流程:

import userEvent from '@testing-library/user-event';
import { render, screen } from '@testing-library/react';

it('should update a value of a time input', async () => {
  const user = userEvent.setup();
  render(
    <label>
      Time:
      <input type="time" defaultValue="10:30" />
    </label>
  );
  const input = screen.getByLabelText('Time:');
  await user.click(input);
  await user.keyboard('{selectall}');
  await user.type(input, '06:45');
  expect(input).toHaveValue('06:45');
});

方案3:模拟粘贴操作

直接使用user.paste()模拟粘贴时间字符串的操作,这种方式会直接覆盖原有值:

import userEvent from '@testing-library/user-event';
import { render, screen } from '@testing-library/react';

it('should update a value of a time input', async () => {
  const user = userEvent.setup();
  render(
    <label>
      Time:
      <input type="time" defaultValue="10:30" />
    </label>
  );
  const input = screen.getByLabelText('Time:');
  await user.paste(input, '06:45');
  expect(input).toHaveValue('06:45');
});

内容的提问来源于stack exchange,提问作者Mirco Bellagamba

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 12:54:56