[英]Test antd dropdown with @testing-library/react
I'm struggling with test which would select some value from dropdown component (antd).我正在努力测试 select 来自下拉组件 (antd) 的一些值。 Here is component that I would like to test:这是我要测试的组件:
import React, { useState } from 'react';
import { Form, Select, Modal } from 'antd';
import 'antd/dist/antd.css';
export const ServiceModal = () => {
const [form] = Form.useForm();
const validateDropdown = () => Promise.resolve();
const tags = [
{ tag: 'one', id: 1 },
{ tag: 'two', id: 2 },
{ tag: 'three', id: 3 },
];
return (
<Form form={form} layout="inline" autoComplete="off" preserve={false}>
<Form.Item label="Tag" name="tag" initialValue={undefined}>
<Select allowClear onChange={validateDropdown}>
{tags.map(({ tag, id }) => (
<Select.Option key={tag} value={id}>
{tag}
</Select.Option>
))}
</Select>
</Form.Item>
</Form>
);
};
and here is the test:这是测试:
import * as React from 'react';
import { render, screen, within } 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('test', () => {
it('test', async () => {
const a = render(<ServiceModal />);
const dropDown = getTagDropdown();
// and here I need to pick some value from dropdown,
// but I don't know how.
});
});
I've tried to follow this example but it fails with:我试图遵循这个例子,但它失败了:
TestingLibraryElementError: Unable to find an accessible element with the role "option" and name "three" TestingLibraryElementError:无法找到角色为“选项”且名称为“三”的可访问元素
probably because antd's dropdown implemented differently than in material-ui in that example.可能是因为 antd 的下拉菜单实现方式与该示例中的 material-ui 不同。 But I'm still have no idea how to do it in my case.但我仍然不知道在我的情况下该怎么做。
packages versions:包版本:
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"@types/jest": "^27.5.2",
"@types/node": "^16.18.3",
"@types/react": "^18.0.25",
"@types/react-dom": "^18.0.8",
"antd": "4.15.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"typescript": "^4.8.4",
"web-vitals": "^2.1.4"
*I have almost no experience in frontend, so any help is much appreciated. *我几乎没有前端经验,所以非常感谢任何帮助。 Thanks in advance!提前致谢!
Something like this?是这样的吗?
describe('test', () => { it('test', async () => { const a = render(<ServiceModal />); const dropDown = getTagDropdown(); userEvent.click(dropDown); const myTag = screen.getByText('one'); expect(myTag ).toBeVisible(); });
You should use something like:你应该使用类似的东西:
const dropDown = screen.getByRole('combobox', { name: 'Tag' });
// Or async if you need to wait some process(loading data), for example
const dropDown = await screen.findByRole('combobox', { name: 'Tag' });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.