1

I want to test antd autocomplete by just ensure, that when user typing something dropdown values will be appearing after fetching data from BE.

And I'm trying to simulate it:

it('user got results while typing something', async () => {
    const { getByTestId } = render(<AutoComplete />);
    const searchInput = getByTestId('autosuggest-trigger')
        .querySelector('.ant-select-selection-search-input');

    fireEvent.focus(searchInput);
    fireEvent.change(searchInput, { target: { value: 'Alice' } });
    expect(searchInput.value).toBe('Alice'); // All is good so far..

    await waitFor(() => {
        expect(
            document.querySelector('.ant-select-dropdown'),
        ).not.toBeNull(); // FAILS
    });
});

I'm getting results BTW in my real app, but can't do a such trick in testing.

What is wrong and how can I solve it?

WebArtisan
  • 3,996
  • 10
  • 42
  • 62

1 Answers1

0

You should try to trigger a click event on the autocomplete suggestion list item which contains "Alice":

it('user got results while typing something', async () => {
  const { getByTestId } = render(<AutoComplete />);
  const searchInput = getByTestId('autosuggest-trigger')
    .querySelector('.ant-select-selection-search-input');

  // in my experience this is not needed
  fireEvent.focus(searchInput);

  // so autocomplete list is open, showing "Alice" option
  fireEvent.change(searchInput, { target: { value: 'Alice' } });
  expect(searchInput.value).toBe('Alice'); // All is good so far..

  // now click on the autocomplete list item
  // in some occasion, many HTML elements matched so I had to use getAllByText then pick to right one
  fireEvent.click(getByText("Alice"));

  await waitFor(() => {
    expect(
      document.querySelector('.ant-select-dropdown'),
    ).not.toBeNull(); // FAILS
  });
});

This is not ideal and should be simplified. And this is not an option if your select is not searchable.

See also https://stackoverflow.com/a/61115234/2295549.

Florian Motteau
  • 3,467
  • 1
  • 22
  • 42