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

React项目使用Jest测试Select组件时出现Lint报错如何解决

Jest测试React Select组件lint报错解决方案

报错根因

两个lint报错都来自同一段写法有误的测试代码:

expect(screen.findByRole('combobox'));

两个错误分别对应两个语法问题:

  • testing-library/await-async-query:Testing Library中所有findBy*前缀的查询都是异步方法,返回Promise类型结果,必须用await接收返回值,否则无法获取到实际渲染的DOM节点。
  • jest/valid-expect:Jest的expect断言必须搭配对应的匹配器(比如toBeInTheDocument()、toHaveValue()等)才能构成合法的断言逻辑,当前代码只传入了查询结果,没有后续匹配判断,不符合Jest语法要求。

代码修正方式

首先修复基础的combobox渲染测试,需要给测试回调加async标记,等待异步查询结果后再做断言:

it('Renders select field option', async () => {
  render(getSelectField());
  const combobox = await screen.findByRole('combobox');
  expect(combobox).toBeInTheDocument();
});

如果要测试选择框内部选项的选择逻辑,需要先模拟用户操作展开下拉菜单,再对选项做交互和断言,参考写法:

// 先引入userEvent用于模拟真实用户操作
import userEvent from '@testing-library/user-event';

it('can select option correctly', async () => {
  const user = userEvent.setup();
  render(getSelectField());
  // 等待combobox渲染完成
  const combobox = await screen.findByRole('combobox');
  // 点击combobox展开下拉选项
  await user.click(combobox);
  // 查找目标选项,替换成你自己的选项文本即可
  const testOption = await screen.findByRole('option', { name: '你的选项文本' });
  // 点击选中选项
  await user.click(testOption);
  // 断言选中结果符合预期,可根据组件实际实现调整匹配规则
  expect(combobox).toHaveTextContent('你的选项文本');
});

提示:模拟用户交互优先使用@testing-library/user-event,相比内置的fireEvent更贴近真实浏览器的用户操作行为,测试结果更可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 10:12:23