Search code examples
reactjssinonjestjsreact-day-picker

jest instace().simulate('dayClick'); TypeError does not exist


I have a component that is using 'react-day-picker'.

This component has a method called handleDayClick:

handleDayClick(e, day, {disabled}) {
        if (disabled) {
            // Do not update the state if the day is disabled
            return;
        }
        this.setState({ selectedDay: day });
        this.props.dateClick(day);
    };

It is then passed to the as the onDayClick prop:

<DayPicker
   onDayClick={ this.handleDayClick.bind(this) }
   selectedDays={ day => DateUtils.isSameDay(day, this.state.selectedDay) }
   disabledDays={ isWeekend }
 />

Now I would like to write a test that simulates a click event on a date to see if it triggers the correct method:

it('DayPicker should call handleDayClick on click', () => {
    const sidebar = mount(<Sidebar />);
    let spy = sinon.spy(sidebar.instance(), 'handleDayClick');
    sidebar.update();
    sidebar.find(DayPicker).simulate('dayClick');
    expect(spy.called).toBe(true);
  });

The problem with this is that the .simulate() does not recognize 'dayClick'. I get the following error in the console:

TypeError: ReactWrapper::simulate() event 'dayClick' does not exist

If I try to simulate 'click' instead, the spy returns false (so the method is never called).

What am I doing wrong?


Solution

  • Simulate only supports events that React understands

    (https://facebook.github.io/react/docs/test-utils.html#simulate)

    This is why you're getting your error on dayClick.

    To simulate the click you should dive into react-day-picker and find out what DOM element the onClick prop eventually gets assigned to. Then simulate the click on that.


    Edit - This is the component that contains the DOM node that gets the click handler

    https://github.com/gpbl/react-day-picker/blob/master/src/Day.js

    You should look to simulate the test on the <div> inside the Day component