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

如何在不使用Jest的情况下用react-testing-library测试Ant Design Select组件

如何在不使用Jest的情况下用react-testing-library测试Ant Design的Select组件

针对你嵌套在Form中的Ant Design Select组件,无需Jest也能通过react-testing-library完成测试,核心是模拟真实用户交互流程,步骤如下:

测试步骤与代码示例

假设你的组件被封装在CountryForm中:

1. 你的组件代码

import { Form, Select } from 'antd';

const CountryForm = () => {
  return (
    <Form>
      <Form.Item
        name="country"
        label="Country"
        rules={[
          {
            message: 'select a country',
            required: true,
          },
        ]}
      >
        <Select options={[{ label: 'Spain', value: 'SP' }]} />
      </Form.Item>
    </Form>
  );
};

export default CountryForm;

2. 测试代码实现

import { render, screen, fireEvent } from '@testing-library/react';
import CountryForm from './CountryForm';
import { Form } from 'antd';

// 获取Form实例的辅助函数
const getFormInstance = (container) => {
  return container.querySelector('[data-testid="form"]')?.__formInstance;
};

// 测试选择选项的流程
const testSelectCountry = () => {
  // 渲染组件
  const { container } = render(<CountryForm />);
  const form = getFormInstance(container);

  // 1. 找到Select触发元素并点击打开下拉
  const selectTrigger = screen.getByRole('combobox', { name: /country/i });
  fireEvent.click(selectTrigger);

  // 2. 定位并点击Spain选项
  const spainOption = screen.getByRole('option', { name: 'Spain' });
  fireEvent.click(spainOption);

  // 3. 验证表单值(不用Jest,用原生断言逻辑)
  const countryValue = form.getFieldValue('country');
  if (countryValue !== 'SP') {
    throw new Error(`期望获取值SP,实际得到${countryValue}`);
  }

  // 4. 验证必填规则:清空选择后触发表单校验
  fireEvent.click(selectTrigger);
  fireEvent.click(screen.getByText('Clear')); // 点击清除选项
  fireEvent.click(screen.getByRole('button', { name: /submit/i })); // 假设存在提交按钮
  const errorMessage = screen.getByText('select a country');
  if (!errorMessage) {
    throw new Error('未显示必填错误提示');
  }
};

// 执行测试
testSelectCountry();

关键注意事项

  • 定位元素用语义化角色:优先用getByRole而非类名,避免Ant Design版本更新导致选择器失效
  • 处理Portal渲染的下拉:react-testing-library默认会查询整个document,无需额外配置即可找到下拉选项
  • 获取Form实例:通过组件DOM元素获取Form实例,用于直接验证字段值
  • 断言方式:不用Jest的话,可使用原生if判断+抛出错误,或Chai等第三方断言库替代

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 19:50:35