1

我试图react-day-pickerhttps://react-day-picker.js.org/examples/selected-multiple进行测试enzymejest但不幸的是我收到了一个错误:TypeError: Cannot read property 'selected' of undefined. 主要是我想测试handleDayClick()方法

我的组件

export default class MultiDayPicker extends Component {
  state = {
    selectedDays: []
  };

  handleDayClick = (day, {selected}) => {
    const {selectedDays} = this.state;

    if (selected) {
      const selectedIndex = selectedDays.findIndex(selectedDay =>
        DateUtils.isSameDay(selectedDay, day)
      );

      selectedDays.splice(selectedIndex, 1);
    } else {
      selectedDays.push(day);
    }

    this.setState({selectedDays});
  };

  render() {
    return (
      <DayPicker
        selectedDays={this.state.selectedDays}
        onDayClick={this.handleDayClick}
      />
    );
  }
}

我的测试:

it('should call the `handleDayClick` function', () => {
    const component = shallow(<MultiDayPicker {...defaultProps} />);

    expect(component.instance().handleDayClick()).toHaveBeenCalled();
  });

我将不胜感激任何想法或帮助,在此先感谢

4

1 回答 1

0

也许你必须在 DayPicker 上添加修饰符道具

<DayPicker
    selectedDays={this.state.selectedDays}
    onDayClick={this.handleDayClick}
    modifier={{selected: this.state.selectedDays}}
 />

于 2021-10-07T08:43:29.327 回答