Swiper 8 和笑话

Rom*_*ban 4 typescript reactjs jestjs es6-modules swiper.js

Swiper 8 和 Jest (支持 ESM) 必须使用 import 加载 ES 模块 在此处输入图像描述 在 此处输入图像描述

如果我需要保留 swiper 8(不降级),我们该如何解决

Mar*_*nes 6

如果有人遇到同样的问题但正在使用NextJs 12.2next/jest并且答案与Francisco Barros 的答案Jest 28有所不同。

// 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)/)',
  ]
})
Run Code Online (Sandbox Code Playgroud)

on可防止 Jest 转换 Swiper 文件,但会影响此包提供的 CSS 文件transformIgnorePatternsjest.config.js

模拟这些CSS文件是配置最小的解决方案。就我而言,在测试时访问这些 CSS 文件并不重要,但如果这些文件与您相关,还有其他方法。

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

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

export {};
Run Code Online (Sandbox Code Playgroud)

我创建了一个存储库来提供必要设置的完整参考。 https://github.com/markcnunes/with-jest-and-esm

请记住,此设置可能必须在未来Next.js/next/js版本中进行更改,但只需共享此方法,以防这对使用相同设置的其他人有用。