0

I have this component and it is using swiper/react. While writing test cases, I'm not able to mock the swiper event it is getting in the onSlideChange. I'm not able to pass through the if condition in the onSlideChangeHandler function. Can anybody help? thanks!

import { Swiper, SwiperSlide } from 'swiper/react';

export default function Abcxyz(props: PropsType) {
...
...

  const onSlideChangeHandler = (swiper) => {
    const activeSlideIndex = swiper.activeIndex;
    const slides = swiper.slides;
    if (slides[activeSlideIndex]?.id === 'hybrid printer bundle') {
      visibleConfigOptionsStore.setVisibleConfigOptions(
        slides[activeSlideIndex].id
      );
    }
  };


  return (
    <Swiper
      onSlideChange={(swiper) => onSlideChangeHandler(swiper)}
    >
  )
}

Tried few things but nothing is working at the moment.

1 Answers1

0

As you do not want to test Swiper itself and you just only want to verify that your handler is executed when onSlideChange is fired, you can do the following:

  1. Mock Swiper so you can now fire the onSlideChange by using a testId and a click event
jest.mock('swiper/react', () => ({
  Swiper: ({ children, onSlideChange }: { children: React.ReactNode; onSlideChange: () => void }) => (
    <div data-testid="swiper" onClick={onSlideChange}>
      {children}
    </div>
  ),
}));
  1. Now fire the event in your test and make any assertions you want:
fireEvent.click(screen.getByTestId('swiper'));
ivan trujillo
  • 301
  • 3
  • 4