当用户单击日历中的日期时,应用程序应将日历的视图更改为单击日期的周视图。您可以在沙箱中试用:https ://codesandbox.io/s/elastic-torvalds-ifedt?file=/src/App.test.js:100-503
您还可以在componentDidMount
方法中看到dateClick
回调是通过事件触发mousedown
的mouseup
。我尝试在测试中模仿这一点,但事件不会使用fireEvent.mouseDown(date)
and触发fireEvent.mouseUp(date)
。
有谁知道如何解决这个问题?
我将尝试使用select
回调并为您提供最新进展。
更新:似乎select
回调遇到了与回调相同的问题dateClick
。也就是说,如果我正确理解源代码,它们都会经历相同的mousedown
事件。mouseup
我已经没有关于如何测试这个处理程序的想法了。任何想法表示赞赏。
应用程序.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)}
/>
);
}
}
应用程序.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();
});