Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • fireEvent.click()
  • fireEvent.focus()
  • fireEvent.select()
  • input.focus()

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?

like image 434
Zach Avatar asked Nov 14 '18 17:11

Zach


People also ask

Does fireEvent need act?

You NEVER need to wrap userEvent or fireEvent in act. They are *already* wrapped in act. Some have noticed that they see an "act warning" go away when wrapping these in an async act.


1 Answers

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...
like image 71
thejohnbackes Avatar answered Oct 17 '22 08:10

thejohnbackes