13

I have recently upgraded my React project to ant design v4 and all the tests that use a Select, AutoComplete or Tooltip are broken. Basically when clicking the components, the modal or select options are not present in JSDOM. This used to work fine in v3.

Can somebody show me how to test antd v4 with react testing library ?

Example:

My Component:

import React from "react";
import "./styles.css";
import { Select } from "antd";

const { Option } = Select;

function handleChange(value) {
  console.log(`selected ${value}`);
}

export default function App() {
  return (
    <div className="App" style={{ marginTop: "40px" }}>
      <Select
        defaultValue="lucy"
        style={{ width: 120 }}
        onChange={handleChange}
      >
        <Option value="jack">Jack</Option>
        <Option value="lucy">Lucy</Option>
        <Option value="disabled" disabled>
          Disabled
        </Option>
        <Option value="Yiminghe">yiminghe</Option>
      </Select>
    </div>
  );
}

My test

import "@testing-library/jest-dom/extend-expect";
import React from "react";
import { render, fireEvent, prettyDOM } from "@testing-library/react";
import App from "./App";

test("App Test", () => {
  const { queryAllByText, getByText, container } = render(<App />);

  expect(queryAllByText("Lucy").length).toBe(1);
  expect(queryAllByText("Jack").length).toBe(0);
  fireEvent.click(getByText("Lucy"));
  console.log(prettyDOM(container));
  // This line fails although I would expect the dropdown to be open and all the options visible
  expect(queryAllByText("Jack").length).toBe(1);
});

Here is a link to a codesandbox that reproduces the issue. (As mentioned, that code used to work in v3).

https://codesandbox.io/s/staging-shape-0xkrl?file=/src/App.test.js:0-494

klugjo
  • 19,422
  • 8
  • 57
  • 75

3 Answers3

34

After losing 2 days on this, here is the problem and solution:

Problem

In antd v3 it used to be possible to open a Select by doing selectHtmlElement.click(). You can test in the chrome dev tools console. In v4 this does not work.

This means that RTL which uses JSDOM under the hood will have the same behaviour. When you do fireEvent.click(selectElement); nothing happens !

Solution

This put me on the right track: https://github.com/ant-design/ant-design/issues/22074

The event you need to trigger is not a click() but a mouseDown() on the first child of the select.

const elt = getByTestId('your-select-test-id').firstElementChild;
fireEvent.mouseDown(elt); // THIS WILL OPEN THE SELECT !

Now at this point you probably want to select an option from the list but there is an animation going on so the following code (that used to work in v3) will also fail.

expect(getByText('Option from Select')).toBeVisible(); // FAILS !

You have 2 options, use toBeInTheDocument() or wait for the animation to be over by using waitFor(...)

Option 1: Faster but not totally accurate, I prefer to use this for simple use cases as it makes the tests faster and synchronous

expect(getByText('Option from Select')).toBeInTheDocument(); // WORKS !

Option 2: Slower as you need to wait for the animation to finish but more accurate for complex cases

await waitFor(() => expect(getByText('Option from Select')).toBeVisible()); // WORKS !
klugjo
  • 19,422
  • 8
  • 57
  • 75
  • 1
    Worth mentionning that fireEvent.change(elt.querySelector('input'), {target:{value:{'Option text'}}) works for searchable selects (only the right option will be visible, and ready to be clicked). – Florian Motteau May 06 '20 at 17:30
  • 1
    works perfect, but instead of `await waitFor()`, you can also use `setInterval(() => expect(), 0)`, you can also just set the `open` prop to `true` instead of doing the `mouseDown` event – Daniel Jun 04 '20 at 13:45
  • How about the tooltip? Did you figure out how to test it? I can't seems to find the tooltip in the test even I put the data-testid @klugjo – Sam Kah Chiin Jul 02 '20 at 07:39
  • 5
    I only lost 20 mins thanks to your 2 days, thank you for this!! – rbennell Jul 08 '20 at 16:50
  • Actually I'm able to `userEvent.click` (`import userEvent from '@testing-library/user-event'`) it to open the dropdown, but when I try to click on the option, it occurss error about `unsable to focus`. – Lai32290 Sep 01 '20 at 20:10
  • To open the dropdown and select an option, this comment saves my life: https://github.com/ant-design/ant-design/issues/22074#issuecomment-662814706 – Rakib Dec 08 '22 at 19:01
6

Looks like now ("antd": "4.17.3", "@testing-library/user-event": "^13.5.0") userEvent.click with { skipPointerEventsCheck: true } works:

const options = [
  { label: "", value: "cat", },
  { label: "", value: "dog", }
];

const onChangeMock = jest.fn();

render(
  <Select
    options={options}
    onChange={onChangeMock}
  />,
);

const select = screen.getByRole("combobox");

userEvent.click(select);

const option = screen.getByText("");

userEvent.click(option, undefined, { skipPointerEventsCheck: true });

expect(onChangeMock).toHaveBeenCalledWith("dog", {
  label: "",
  value: "dog",
});
sad comrade
  • 1,341
  • 19
  • 21
0

Unfortunately @klugjo answer did not work for me with antd-mobile's Radio component.

I solved the issue with adding an extra onClick property to the component:

<Radio.RadioItem
    key={key}
    checked={isSelected}
    onChange={onChange}
    onClick={onChange} // needed for rtl
    >
    {label}
</Radio.RadioItem>

This is not a clean solution, as it modifies the production code for testing. It might miss a failure on a TouchEvent, but this should be an issue to the antd-mobile library – not this test.

pico_prob
  • 1,105
  • 10
  • 14