3

When the user clicks on the date in the calendar, the app should change the calendar's view to the week view of the clicked date. You can try it out in the sandbox: https://codesandbox.io/s/elastic-torvalds-ifedt?file=/src/App.test.js:100-503

You can also see in the componentDidMount method that the dateClick callback is triggered with mousedown and mouseup events. I tried mimicking this in the tests but the events do not fire using fireEvent.mouseDown(date) and fireEvent.mouseUp(date).

Does anyone have an idea on how to solve this?

I will try using the select callback and give you an update on how that went.

Update: It seems that select callback suffers from the same problem as the dateClick callback. Namely, they both go through the same mousedown and mouseup events, if I understood the source code properly. I am running out of ideas on how to test this handlers. Any ideas are appreciated.

App.js

class Calendar extends React.Component {
  constructor(props) {
    super(props);
    this.calendarRef = React.createRef();
  }

  componentDidMount() {
    const today = this.formatDate(new Date(), 'yyyy-mm-dd');
    const gridcell = document.querySelector(`[data-date='${today}']`);

    // triggers FullCalendar's dateClick callback, it only works if mouseup is fired after mousedown
    setTimeout(() => {
      gridcell.dispatchEvent(new MouseEvent('mousedown', { bubbles: true }));
      gridcell.dispatchEvent(new MouseEvent('mouseup', { bubbles: true }));
    }, 2000);
  }

  handleDateClicked(info) {
    this.openWeekView(info.dateStr);
  }

  openWeekView(date) {
    const calendarApi = this.calendarRef.current.getApi();
    calendarApi.changeView('dayGrid', date);
  }

  formatDate(date, format) {
    const map = {
      yyyy: date.getFullYear().toString(),
      mm: date.getMonth() + 1,
      dd: date.getDate().toString(),
    };
    return format.replace(/yyyy|mm|dd/gi, (matched) => map[matched]);
  }

  render() {
    return (
      <FullCalendar
        ref={this.calendarRef}
        plugins={[dayGridPlugin, interactionPlugin]}
        initialView="dayGridMonth"
        dateClick={(info) => this.handleDateClicked(info)}
      />
    );
  }
}

App.test.js

test('clicking on gridcell opens the week view', async () => {
  render(<Calendar />);

  // user open todays date
  const today = new Date().toLocaleString('en-US', {
    month: 'long',
    day: '2-digit',
    year: 'numeric',
  });

  // this is the cell that user clicks on to open the date in the week view
  const gridcell = screen.getByRole('gridcell', { name: today });

  // this two are supposed to trigger the FullCalendar's dateClick callback,
  // the same way they are being triggered in the componentDidMount
  fireEvent.mouseDown(gridcell);
  fireEvent.mouseUp(gridcell);

  // when the date is clicked, the user will be able to see the today's date string
  expect(screen.getByText(`${today}`)).toBeInTheDocument();
});
Filip
  • 31
  • 2

0 Answers0