ant-design: Cannot test Select with react testing library after upgrading to v4

  • I have searched the issues of this repository and believe that this is not a duplicate.

Reproduction link

Edit on CodeSandbox

Steps to reproduce

Given the following component

<Select
  defaultValue="Value 1"
  onChange={handleChange}
>
  <Option value="jack">Value 1</Option>
  <Option value="jack">Value 2</Option>
  <Option value="jack">Value 3</Option>
</Select>

In v3 is it possible to test a Select component like this:

// Opens the Drop down
fireEvent.click(getByText("Value 1"));
// Select a value from the dropdown <- THIS FAILS in v4 but work in v3
fireEvent.click(getByText("Value 2"));

When printing out the full DOM, the dropdown content is not present in the DOM. This means I can’t select an option.

This is a blocker to migrate my app to v4

What is expected?

I would expect the dropdown content to be inside the DOM at the bottom of the body.

What is actually happening?

The content of the dropdown is not appearing anywhere

Environment Info
antd 4.1.1
React 16.12.0
System All
Browser Chrome

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Comments: 15 (4 by maintainers)

Most upvoted comments

Don’t depend on dom manipulation to control component, it is not reliable.

Try <Select virtual={false} />

@xyy94813 does your dropdown look like this? I’m unable to use @testing-library/user-event to simulate click when there’s pointer-events: none. it seems like the animation hasn’t been performed yet, even with jest.runAllTimers()

<div
  class="ant-select-dropdown"
  style="opacity: 0; pointer-events: none; min-width: 0; width: 0px;"
> 

https://github.com/ant-design/ant-design/issues/22074#issuecomment-597061052

This fixed it.

Basically .click() does not work anymore. mouseDown() needs to be used instead

Thanks !

it works for me in antd v4.16.2

import {
  cleanup,
  render,
  fireEvent,
  act,
  screen,
  waitFor,
} from '@testing-library/react';

test('Tree select', async () => {
  const onChangeHandler = jest.fn();
  const { container } = render(<AreaTreeSelect onChange={onChangeHandler} />);
  // open dropdown of tree select
  await act(async () => {
      fireEvent.mouseDown(
        container.querySelector('.ant-select-selection-search-input'),
      );
      jest.runAllTimers();
  });
})

For anyone who finds this, the following is working for me

// Show the dropdown
userEvent.click(screen.getByText('select text'));

// Hide the dropdown
userEvent.click(container);

I did not succeed selecting a value using Cypress either using click() or trigger('mouseDown').

If you use <Select showSearch={true}> you may be able to type a value in the search box in order to select a value. In case of Cypress + Testing Library:

cy.findByRole('combobox', { name: /your label here/i}).type("some value{enter}");