How to Resolve 'Cannot use import statement outside a module' Error when Mocking Swiper JS with Jest

7 min read.
Tags: javascriptjestunit-test

If Jest throws Cannot use import statement outside a module while testing Swiper components, your Jest config is likely skipping transform for ESM packages.

This is common with modern packages that ship ESM by default.

Why this error happens

Jest often ignores node_modules during transform. But some modules (like Swiper) still need Babel/ts-jest transform in your test env.

So Jest reads ESM syntax directly and crashes.

Fix in jest config

Allow Swiper to be transformed:

module.exports = {
  transformIgnorePatterns: [
    '/node_modules/(?!(swiper|ssr-window|dom7)/)'
  ],
};

This tells Jest: ignore most node_modules, but not these packages.

If using Next.js + Babel

Make sure transform is configured too:

transform: {
  '^.+\.(js|jsx|ts|tsx)$': 'babel-jest',
},

Without a transform engine, allow-list alone will not help.

Mock Swiper for simpler unit tests

If you do not need real Swiper behavior in unit tests, mock it:

jest.mock('swiper/react', () => ({
  Swiper: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
  SwiperSlide: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
}));

This keeps tests focused on your component logic.

Related Posts
Latest Posts