Zach
Zach

Reputation: 891

react-testing-library - fireEvent.select() not working

I'm currently running some tests for a project I'm working on, and am having trouble using fireEvent.select() as a way to focus on an input field.

My test so far:

it('is not working :(', () => {
  const input = queryByPlaceholderText('blah');

  fireEvent.change(input, {
    target: {value: 'some text'},
  });

  expect(input).toHaveAttribute('value', 'some text');

  fireEvent.select(input); <-- issue here
});

The component I am testing has a dropdown menu that is only exposed when the input is focused on, but it seems like neither fireEvent.change() nor fireEvent.select() are focusing on the field. I know that fireEvent.change() changes the input value.

So far, I have tried:

but none of those options worked.

I need to be able to select an option in this dropdown menu to be able to properly test the component.

TL;DR

Is there a way to focus on an input field with RTL?

Upvotes: 9

Views: 7754

Answers (1)

thejohnbackes
thejohnbackes

Reputation: 1255

In order to get this to work with React-Select, I had to use ReactDOM instead of fireEvent. Then I could test/run assertions with react-testing-library as normal.

import ReactDOM from 'react-dom';
import TestUtils from 'react-dom/test-utils';

export const openDropdown = ($container) => {
  // Opens the dropdown
  // eslint-disable-next-line react/no-find-dom-node
  selectOption(ReactDOM.findDOMNode($container).querySelector('.Select-arrow'));
};

export const selectOption = ($container) => {
  // Selects an option from the dropdown
  TestUtils.Simulate.mouseDown($container, { button: 0 });
};
    const $fooSelect = await waitForElement(() => app.getByTestId('foo-select'));
    openDropdown($fooSelect);
    const $fooElement = await waitForElement(() => app.getByText(fooFixture[0].name));

    selectOption($fooElement);

    await wait()
    // do stuff...

Upvotes: 3

Related Questions