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

Antd Select组件测试仅显示2个选项,如何让更多选项可见?

解决Antd Select测试环境下无法加载2个以上选项的问题

问题根源

Antd Select的下拉框默认有高度限制,超过限制的选项会被隐藏在滚动区域内,而Testing Library的getAllByRole等查询方法默认只返回可见元素,导致测试时只能获取到前2个可见选项。另外原测试代码的it回调函数缺少async关键字,会导致await语法报错,这也是需要修正的点。

解决方案

方案1:修改下拉框样式,显示所有选项

在测试用的Select组件上添加dropdownStyle属性,取消高度限制,让下拉框自适应显示所有选项:

function Tmp() {
  return (
    <Select dropdownStyle={{ maxHeight: 'none' }}>
      <Select.Option value='1'>1</Select.Option>
      <Select.Option value='2'>2</Select.Option>
      <Select.Option value='3'>3</Select.Option>
    </Select>
  );
}

修改后所有选项会直接显示在下拉框中,测试时能通过getAllByRole获取到全部选项。

方案2:查询时包含隐藏元素

如果不想修改组件样式,可以在查询选项时指定hidden: true,让Testing Library返回所有(包括隐藏的)选项元素:

const options = screen.getAllByRole('option', { hidden: true });

注意:这种方式可能会返回Select内部的占位类隐藏元素,需要结合文本断言精准匹配目标选项。

方案3:模拟滚动到隐藏选项

如果需要贴近真实用户操作,可以先找到下拉容器,再滚动到目标选项位置:

await user.click(screen.getByRole('combobox'));
// 找到下拉容器
const dropdown = screen.getByRole('listbox');
// 找到第三个选项
const thirdOption = screen.getByText('3');
// 滚动到选项位置
await user.scrollIntoView(thirdOption, { container: dropdown });
// 再查询所有选项
const options = screen.getAllByRole('option');

修改后的完整测试代码(方案1)

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

describe('Select', () => {
  let user: ReturnType<typeof userEvent.setup>;

  beforeAll(() => {
    user = userEvent.setup();
  });

  it('shows more than 2 options', async () => {
    function Tmp() {
      return (
        <Select dropdownStyle={{ maxHeight: 'none' }}>
          <Select.Option value='1'>1</Select.Option>
          <Select.Option value='2'>2</Select.Option>
          <Select.Option value='3'>3</Select.Option>
        </Select>
      );
    }

    render(<Tmp />);

    await user.click(screen.getByRole('combobox'));
    const options = screen.getAllByRole('option');
    
    expect(options).toHaveLength(3);
    expect(within(options[0]).getByText('1')).toBeInTheDocument();
    expect(within(options[1]).getByText('2')).toBeInTheDocument();
    expect(within(options[2]).getByText('3')).toBeInTheDocument();
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 09:41:18