【问题标题】:Test antd dropdown with @testing-library/react使用 @testing-library/react 测试 antd 下拉列表
【发布时间】:2023-02-04 11:39:36
【问题描述】:

我正在努力进行测试,该测试将从下拉组件(antd)中选择一些值。 这是我要测试的组件:

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>
  );
};

这是测试:

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.
  });
});

我尝试按照this 示例进行操作,但失败了:

TestingLibraryElementError:无法找到角色为“选项”且名称为“三”的可访问元素

可能是因为 antd 下拉菜单的实现方式与该示例中的 material-ui 不同。但我仍然不知道在我的情况下该怎么做。

包版本:

    "@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"

*我几乎没有前端经验,所以非常感谢任何帮助。提前致谢!

【问题讨论】:

    标签: reactjs antd web-frontend testing-library


    【解决方案1】:

    是这样的吗?

    describe('test', () => {
      it('test', async () => {
        const a = render(<ServiceModal />);
        const dropDown = getTagDropdown();
        userEvent.click(dropDown);
        const myTag = screen.getByText('one');
        expect(myTag ).toBeVisible();
      });

    【讨论】:

      【解决方案2】:

      你应该使用类似的东西:

      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' });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-05-21
        • 2019-11-11
        • 1970-01-01
        • 1970-01-01
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 2019-08-29
        相关资源
        最近更新 更多