在疯狂地进行了一个拒绝通过的测试之后,我意识到 Antd 库中的 Select 组件不能处理超过 2 个选项。我编写了以下测试来探讨这个问题:
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', () => {
function Tmp() {
return (
<Select>
<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();
});
});
此测试失败。首先它在以下行失败:
expect(options).toHaveLength(3);
它说
options
的长度只有2。
当我删除该行时,测试在最后一次期望时失败:
expect(within(options[2]).getByText('3')).toBeInTheDocument();
它表示
options[2]
不是一个元素。如何在测试中的“选择”组件中提供更多选项?
“antd”:“^5.14.2”
原因是
virtual
组件的 <Select/>
属性默认为 true
。它将使用虚拟列表。如果 virtual
属性设置为 false
,则测试将起作用。
此外,你忘记使用
async
import { Select } from 'antd';
import { render, screen, within } from '@testing-library/react';
import '@testing-library/jest-dom';
import userEvent from '@testing-library/user-event';
import React from 'react';
describe('Select', () => {
let user: ReturnType<typeof userEvent.setup>;
beforeAll(() => {
user = userEvent.setup();
});
it('shows more than 2 options', async () => {
function Tmp() {
return (
<Select virtual={false}>
<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();
});
});
测试结果:
Select
√ shows more than 2 options (306 ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 2.426 s, estimated 3 s
Ran all test suites related to changed files.