Testing Swiper with Jest
P粉805931281
P粉805931281 2023-08-31 22:35:14
0
1
737
<p>I have a component that uses swiper/react. While writing the test case, I am unable to simulate the swiper event obtained in onSlideChange. I can't pass the if condition in the onSlideChangeHandler function. Can anyone help? Thanks! </p> <pre class="brush:php;toolbar:false;">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)} > ) }</pre> <p>Tried a few things but nothing is working so far. </p>
P粉805931281
P粉805931281

reply all(1)
P粉384679266

Since you don't want to test Swiper itself and just want to verify that your handler executes when onSlideChange is triggered, you can follow these steps:

  1. Mock Swiper so you can use testId and click events to trigger onSlideChange
jest.mock('swiper/react', () => ({
  Swiper: ({ children, onSlideChange }: { children: React.ReactNode; onSlideChange: () => void }) => (
    <div data-testid="swiper" onClick={onSlideChange}>
      {children}
    </div>
  ),
}));
  1. Now trigger the event and make any assertions in your test:
fireEvent.click(screen.getByTestId('swiper'));
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template