'React/Jest - How to simulate touch "swipe" event
I have a component that triggers a function call whenever a swipe interaction was done. This swipe interaction can either be executed by touchEvent or mouseEvent. My goal was to check if the function was called, whenever a swipe occured. But I fail to simulate the touchEvent in a jest test. Using swiper, react, react-testing-library and jest.
Online Editor link for testing: Codesandbox
The actual class
const App = ({ funcCalledOnSlideChange }) => {
return (
<Swiper
pagination={{
clickable: true
}}
modules={[Pagination]}
watchOverflow
onSlideChange={funcCalledOnSlideChange}
>
<SwiperSlide>
<img className="slide" />
</SwiperSlide>
<SwiperSlide>
<img className="slide-second" />
</SwiperSlide>
</Swiper>
);
};
And the actual test
const mockFunc = jest.fn();
function sendTouchEvent({ x, y, element, eventType }) {
const touchObj = new Touch({
identifier: Date.now(),
target: element,
clientX: x,
clientY: y,
radiusX: 2.5,
radiusY: 2.5,
rotationAngle: 10,
force: 0.5
});
const touchEvent = new TouchEvent(eventType, {
cancelable: true,
bubbles: true,
touches: [touchObj],
targetTouches: [],
changedTouches: [touchObj]
});
element.dispatchEvent(touchEvent);
}
test("should swipe by touch event", async () => {
const { container } = render(<App funcCalledOnSlideChange={mockFunc} />);
const swiperSlide = container.querySelector(".swiper-slide");
act(() => {
sendTouchEvent({
x: 350,
y: 100,
element: swiperSlide,
eventType: "touchstart"
});
sendTouchEvent({
x: 200,
y: 100,
element: swiperSlide,
eventType: "touchmove"
});
sendTouchEvent({
x: 150,
y: 100,
element: swiperSlide,
eventType: "touchend"
});
});
await waitFor(() => {
expect(mockFunc).toBeCalled();
});
});
Actual error:
Failed to construct 'Touch': Failed to read the 'target' property from 'TouchInit': Failed to read the 'target' property from 'TouchInit': Required member is undefined.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
