Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swiper 8 and jest

Swiper 8 and Jest (support ESM) Must use import to load ES Module enter image description here enter image description here

How we can solve if I need to keep swiper 8 (without downgrade)

like image 379
Roman Chaban Avatar asked Sep 15 '25 22:09

Roman Chaban


1 Answers

In case someone runs into this same issue but is using NextJs 12.2, next/jest and Jest 28 the answer is a variation from Francisco Barros' answer.

// jest.config.js
const nextJest = require('next/jest')

const createJestConfig = nextJest({
  // Path to Next.js app to load next.config.js
  dir: './'
})

/** @type {import('@jest/types').Config.InitialOptions} */
const customJestConfig = {
  /**
   * Custom config goes here, I am not adding it to keep this example simple.
   * See next/jest examples for more information.
   */
 }

module.exports = async () => ({
  /**
   * Using ...(await createJestConfig(customJestConfig)()) to override transformIgnorePatterns
   * provided byt next/jest.
   * 
   * @link https://github.com/vercel/next.js/issues/36077#issuecomment-1096635363
   */
  ...(await createJestConfig(customJestConfig)()),
  /**
   * Swiper uses ECMAScript Modules (ESM) and Jest provides some experimental support for it
   * but "node_modules" are not transpiled by next/jest yet.
   *
   * @link https://github.com/vercel/next.js/issues/36077#issuecomment-1096698456
   * @link https://jestjs.io/docs/ecmascript-modules
   */
  transformIgnorePatterns: [
    'node_modules/(?!(swiper|ssr-window|dom7)/)',
  ]
})

The transformIgnorePatterns on jest.config.js prevents the Swiper files from being transformed by Jest but it affects the CSS files that are provided by this package.

Mocking these CSS files is the solution with the smallest configuration. In my case, it didn't matter much about having access to these CSS files while testing but there are other approaches if these files are relevant to you.

// jest.setup.js
import "@testing-library/jest-dom/extend-expect";

jest.mock("swiper/css", jest.fn());

export {};

I created a repository for a full reference of the necessary setup. https://github.com/markcnunes/with-jest-and-esm

Have in mind this setup might have to change for future Next.js / next/js versions but just sharing this approach in case this is useful for other people using this same setup.

like image 132
Mark Nunes Avatar answered Sep 19 '25 04:09

Mark Nunes