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

如何使用@testing-library/user-event实现输入框失焦操作?

使用@testing-library/user-event实现输入框失焦的方案

当然有基于@testing-library/user-event的替代方案,它的优势是模拟真实用户行为,而非直接触发DOM事件,更贴近实际使用场景。以下是两种常用方式:

1. 点击输入框外的区域

模拟用户点击页面其他元素(比如body、其他控件),自然触发输入框失焦:

import userEvent from '@testing-library/user-event';

test('输入框点击外部失焦', async () => {
  const user = userEvent.setup();
  const input = screen.getByRole('textbox');

  // 先聚焦输入框
  await user.click(input);
  // 点击页面空白区域触发失焦
  await user.click(document.body);
});

2. 使用Tab键切换焦点

通过按Tab键将焦点转移到下一个可聚焦元素,当前输入框会自动失焦:

import userEvent from '@testing-library/user-event';

test('通过Tab键切换焦点让输入框失焦', async () => {
  const user = userEvent.setup();
  const input = screen.getByRole('textbox');
  // 确保页面存在另一个可聚焦元素,比如按钮
  const nextElement = screen.getByRole('button');

  await user.click(input);
  // 按Tab键转移焦点
  await user.tab();
});

针对旧版本user-event(v13及以下)的写法

如果你的项目使用的是v13或更早版本,无需调用setup(),直接使用方法即可:

import userEvent from '@testing-library/user-event';

test('输入框失焦测试', async () => {
  const input = screen.getByRole('textbox');
  
  await userEvent.click(input);
  await userEvent.click(document.body);
});

相比fireEvent.blur,上述方法更符合用户真实操作路径,测试结果也更可靠。

内容的提问来源于stack exchange,提问作者Allan Juan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 05:43:19