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

如何用@testing-library/react测试Ant Design下拉选择组件?

解决Ant Design Select组件的React Testing Library测试问题

Ant Design 4.x版本的Select组件实现逻辑和Material UI不同,它会将下拉选项通过Portal渲染到body上,且选项的ARIA角色是menuitem而非option,这是你遇到错误的核心原因。以下是修正后的测试方案:

修正后的测试代码

import * as React from 'react';
import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { ServiceModal } from './service-modal';

const getTagDropdown = () =>
  screen.getByRole('combobox', {
    name: /tag/i,
  });

describe('ServiceModal', () => {
  it('should select an option from the dropdown', async () => {
    render(<ServiceModal />);
    const dropDown = getTagDropdown();
    
    // 1. 点击下拉框展开选项
    await user.click(dropDown);
    
    // 2. 等待并找到目标选项(注意角色是menuitem)
    const targetOption = await screen.findByRole('menuitem', { name: /three/i });
    
    // 3. 点击选中选项
    await user.click(targetOption);
    
    // 4. 验证选择结果:检查下拉框显示的文本
    expect(dropDown).toHaveTextContent('three');
  });
});

关键说明

  • 打开下拉框:必须先通过点击combobox触发下拉选项的渲染,否则无法找到选项元素
  • 角色匹配:AntD的下拉选项使用menuitem角色,而非Material UI的option,这是你之前报错的直接原因
  • 异步等待:使用await处理用户交互和元素查找,确保组件完成渲染后再执行下一步操作
  • 结果验证:通过检查下拉框的文本内容确认选项已被选中,也可以结合Form的实例验证表单值是否正确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 22:10:29