hypeserver / react-date-range

A React component for choosing dates and date ranges.
MIT License
2.57k stars 658 forks source link

Jest / React Testing Library click event on day does not trigger onChange or onRangeFocusChange #549

Closed spencermehta closed 2 years ago

spencermehta commented 2 years ago

React Testing Library click event does not trigger onRangeFocusChange

Using react-date-range DateRange component, and have custom beginDate and endDate inputs that display the selected dates, and show focus of whether start or end of range is being selected.

Writing jest test for functionality of select start of range, which should cause the endDate input component to become focused, via a function passed to onRangeFocusChange prop.

Using Jest and React Testing Library to get the <button> component of a particular day, and using fireEvent.click() however does not trigger the onChange or the onRangeFocusChange handlers.

 it.only('focuses endDate on selection of beginDate () => {
   const { getAllByText, getByTestId } = render(<Component />);

   const BeginDateInputField = getByTestId('begin-date-input-field');
   BeginDateInputField.focus();
   const nineteenths = getAllByText('19');
   const nineteenth = nineteenths[0];
   expect(nineteenth).toBeTruthy();

   const nineteenthButton = nineteenth.closest('button') as HTMLButtonElement;

   fireEvent.click(nineteenthButton);

   const EndDateInputField = getByTestId('end-date-input-field');
   expect(EndDateInputField).toHaveFocus();
 });

Environment

Package Version: 1.4.0 React version: 17.0.2 Node version: 16.13.2 Browser: N/A - Jest

spencermehta commented 2 years ago

Solved: use userEvent rather than fireEvent

raDiesle commented 2 years ago

@spencermehta I had the same issue. So the key point is to "focus" the element first, after to click on it.