Added Swiper (https://swiperjs.com/react) to my project and tried to set up tests for my component. But after trying different approaches I failed to find working config.
So my question would be, how to test react component with Swiper using Jest and @testing-library/react?
My jest.config.js:
module.exports = {
// preset: 'ts-jest/presets/js-with-ts',
transform: {
// '^.+\\.tsx?$': 'ts-jest',
'^.+\\.(js|jsx|ts|tsx)$': 'ts-jest',
},
collectCoverage: true,
coverageReporters: ['lcov'],
testRegex: '(.*(\\.|/)(test|spec))\\.(jsx?|tsx?)$',
testResultsProcessor: 'jest-sonar-reporter',
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
setupFiles: ['<rootDir>/setup.ts'],
setupFilesAfterEnv: ['<rootDir>/setupAfterEnv.ts'],
moduleNameMapper: {
'swiper/react': '<rootDir>/node_modules/swiper/react/swiper-react.js',
},
testEnvironmentOptions: {
url: 'http://localhost',
},
testEnvironment: 'jsdom',
globals: {
'ts-jest': {
isolatedModules: true,
},
},
transformIgnorePatterns: ['/node_modules/(?!swiper|swiper/react|ssr-window|dom7)'],
};
My component:
import React, { VFC } from 'react';
import { Swiper, SwiperSlide, SwiperProps } from 'swiper/react';
type GalleryImage = {
src: string;
altText?: string;
};
type Props = {
gallery: GalleryImage[];
};
export const Gallery: VFC<Props> = ({
gallery,
}) => {
const settings: SwiperProps = {
slidesPerView: 1,
slidesPerGroup: 1,
};
if (!gallery?.length) {
return null;
}
return (
<Swiper {...settings}>
{gallery?.map((item) => (
<SwiperSlide key={item.src}>
<img src={item.src} alt={item.altText} />
</SwiperSlide>
))}
</Swiper>
);
};
And my test file:
import React, { ComponentProps } from 'react';
import { cleanup, render } from '@testing-library/react';
import { Gallery } from '../';
type GalleryProps = ComponentProps<typeof Gallery>;
const props: GalleryProps = {
gallery: [
{ src: 'image1', altText: 'image no. 1' },
{ src: 'image2', altText: 'image no. 2' },
{ src: 'image3', altText: 'image no. 3' },
],
};
describe('<Gallery/>', () => {
afterEach(cleanup);
it('handles empty gallery', () => {
expect(render(<Gallery gallery={[]} />).container).toBeEmptyDOMElement();
});
describe('when in Desktop view', () => {
it('should show current image in slider', () => {
render(<Gallery {...props} />);
});
});
});
After runnning a test I receive an error:
(0 , dom_js_1.default)(...).children is not a function
TypeError: (0 , dom_js_1.default)(...).children is not a function
at getWrapper (/home/x/projects/styleguide/node_modules/swiper/core/core.js:473:23)
at Swiper.Object.<anonymous>.Swiper.mount (/home/x/projects/styleguide/node_modules/swiper/core/core.js:480:22)
at Swiper.Object.<anonymous>.Swiper.init (/home/x/projects/styleguide/node_modules/swiper/core/core.js:510:28)
at mountSwiper (/home/x/projects/styleguide/node_modules/swiper/components-shared/mount-swiper.js:30:10)...
Reproducable example can be found here: https://github.com/augustas2/swiper-test
Any help is much appreciated.