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.
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.
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.
Is there a way to focus on an input field with RTL?
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.
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...
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With