React/Jest - 如何模拟触摸“滑动”事件

IT技术 javascript reactjs jestjs swiper.js
2022-07-28 01:38:40

我有一个组件,只要完成滑动交互,就会触发函数调用。这种滑动交互可以由 touchEvent 或 mouseEvent 执行。我的目标是检查是否调用了该函数,无论何时发生滑动。但我无法在开玩笑的测试中模拟 touchEvent使用 swiper、react、react-testing-library 和 jest。

用于测试的在线编辑器链接:Codesandbox

实际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>
  );
};

和实际测试

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();
  });
});

实际错误:

Failed to construct 'Touch': Failed to read the 'target' property from 'TouchInit': Failed to read the 'target' property from 'TouchInit': Required member is undefined.
0个回答
没有发现任何回复~