1

I'm struggling with test which would select some value from dropdown component (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"

probably because antd's dropdown implemented differently than in material-ui in that example. 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!

i474232898
  • 781
  • 14
  • 25

2 Answers2

0

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' });
Dercilio
  • 101
  • 5
-1

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();
  });
Mike Bely
  • 21
  • 4