A simple React Select control with only options and a blur handler works perfectly inside my application (i.e. in the browser) but the blur handler is called when I select an option within an automated test.
All libraries are up-to-date at the time of writing:
- React 18.2
- React Select 5.7.3
- Jest with jsdom 29.5.0
- Testing Library user-event 14.4.3
This is simplest code I could come up with to reproduce the problem:
import React from "react";
import {expect} from '@jest/globals';
import {createRoot} from "react-dom/client";
import {act} from "react-dom/test-utils";
import userEvent from '@testing-library/user-event';
import Select from "react-select";
test('it does not fire a blur event when an option is selected', async () => {
let blurCount = 0;
const options = [{label: 'a', value: 'a'}];
// render the control
const container = document.createElement("div");
document.body.appendChild(container);
const user = userEvent.setup();
act(() => {
createRoot(container).render(
<Select
options={options}
classNames={{menu: () => 'select-menu'}}
onBlur={() => {blurCount++}}
/>
);
});
// focus the control by clicking
await act(async () => {
let input = document.querySelector('input');
await user.click(input);
});
// select the first option by clicking
await act(async () => {
let menu = document.querySelector('.select-menu');
const firstOption = menu.children[0].children[0];
await user.click(firstOption);
});
expect(blurCount).toBe(0); // fails because blur count is 1
});
I cannot figure out what causes the blur. It seems to be independent of the click event. It also happens when I simulate text entry and the 'Enter' key in the test. It also happens when I set the menuIsOpen
property to true
. In my test the user interaction does not end with selecting an option so I have to be able to continue after the selection without the blur event happening.
If you can recommend another library for testing this would help as well if it does not lead to the same problem.