I suppose you are having issues with Swiper 7 or newer versions because Jest doesn't support ESM packages yet.
SOLUTION 1:
For Swiper 7-9 or newer versions:
First add the swiper/css
to jest's moduleNameMapper
in package.json
"jest": {
"moduleNameMapper": {
"swiper/css": "swiper/swiper.min.css"
}
}
Second, you can mock Swiper component to render its children:
jest.mock('swiper/react', () => ({
Swiper: ({ children }) => <div data-testid="swiper-testid">{children}</div>,
SwiperSlide: ({ children }) => (
<div data-testid="swiper-slide-testid">{children}</div>
),
}))
In case you have also import any additional modules e.g:
// For Swiper 7-9
import { Navigation, Pagination, Scrollbar, A11y } from 'swiper';
- For Swiper 10-11 or newer versions:
// For Swiper 10-11 or newer versions
import { Navigation, Pagination, Scrollbar, A11y } from 'swiper/modules';
You can just mock the modules like this:
jest.mock('swiper', () => ({
Navigation: (props) => null,
Pagination: (props) => null,
Scrollbar: (props) => null,
A11y: (props) => null,
}))
- For Swiper 10-11 or newer versions:
jest.mock('swiper/modules', () => ({
Navigation: (props) => null,
Pagination: (props) => null,
Scrollbar: (props) => null,
A11y: (props) => null,
}))
Finally, as an example now you can write a test that checks how many slides rendered as a child of "swiper-slide-testid":
test('Renders component with 12 slides', () => {
render(<Component/>)
const slides = screen.getAllByTestId('swiper-slide-testid')
expect(slides.length).toBe(12)
})
SOLUTION 2:
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 [email protected]
And import it this way:
import { Swiper, SwiperSlide } from 'swiper/react'
import 'swiper/swiper-bundle.min.css'
import 'swiper/swiper.min.css'