How can I test swiper with Jest?

Viewed 3511

I'm creating unit testing of Swiper using Jest.

Here is my code:

https://codesandbox.io/s/swiper-default-react-forked-v0dnz?file=/src/App.test.jsx

ā— Test suite failed to run

    Cannot find module 'swiper/react' from 'src/App.jsx'

    Require stack:
      src/App.jsx
      src/App.test.jsx

      1 | import React from "react";
      2 | // Import Swiper React components
    > 3 | import { Swiper, SwiperSlide } from "swiper/react";
        | ^
      4 |
      5 | // Import Swiper styles
      6 | import "swiper/css";

      at Resolver.resolveModule (node_modules/jest-resolve/build/resolver.js:322:11)
      at Object.<anonymous> (src/App.jsx:3:1)

This error has been reported all the time, but the program can run normally. Can anyone help me solve this problem?

3 Answers

I suppose you are having issues with Swiper 7 or newer versions because Jest doesn't support ESM packages yet.

So even if it is not the most optimal solution, you can solve it by downgrading it to Swiper 6

Run these commands:

npm uninstall swiper
npm install swiper@6.8.4

And import it this way:

import { Swiper, SwiperSlide } from 'swiper/react'
import 'swiper/swiper-bundle.min.css'
import 'swiper/swiper.min.css'

This seemed to work for me (Swiper v8):

(in package.json)

  "jest": {
    "moduleNameMapper": {
      "swiper/react": "swiper/react/swiper-react.js",
      "swiper/css": "swiper/swiper.min.css"
    },
    "transform": {
      "^.+\\.css$": "jest-transform-css"
    }
  }

(and maybe also add this to transformIgnorePatterns)

'node_modules/(?!(swiper|ssr-window|dom7)/)'

If you don't care about testing Swiper v8 functionality, but want to test some other features in your components, try to add this line in your jest file:

jest.mock('Swiper', () => class Mocked {});

Worked for nextjs, doesn't complain. Maybe not the best way, but in my case it's more than enough.

Related