Nextjs 和 Jest 变换/transformIgnorePatterns 不适用于 esm 模块

Tay*_*tin 8 reactjs jestjs next.js

我对此进行了大量研究,并找到了相当多的解决方案。我已经找到了一种解决方法,并且希望能够正常transform工作transformIgnorePatterns。然而,我唯一能做的似乎就是在我的__mocks__文件夹中手动添加一些模拟模块。

不确定这是否是由于使用Nextjswith引起Jest的?

这是我的jest.config.js

const nextJest = require("next/jest");

const esModules = ["react-markdown", "rehype-raw", "remark-gfm"].join("|");

const createJestConfig = nextJest({
  // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
  dir: "./",
});

// Add any custom config to be passed to Jest
const customJestConfig = {
  setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
  moduleNameMapper: {
    // Handle module aliases (this will be automatically configured for you soon)
    "^@/components/(.*)$": "<rootDir>/components/$1",

    "^@/pages/(.*)$": "<rootDir>/pages/$1",
  },
  testEnvironment: "jest-environment-jsdom",
  transform: {
    [`(${esModules}).+\\.js$`]: "babel-jest",
  },
  transformIgnorePatterns: [
    `[/\\\\]node_modules[/\\\\](?!${esModules}).+\\.(js|jsx|mjs|cjs|ts|tsx)$`,
  ],
};

// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);
Run Code Online (Sandbox Code Playgroud)

我读到我babel.config.js也需要一个。这是该文件:

module.exports = {
  presets: ["next/babel", "@babel/preset-env"],
};
Run Code Online (Sandbox Code Playgroud)

Mar*_*nes 13

如果有人遇到同样的问题但正在使用NextJs 12.2,next/jest和 ,这里有一个解决方案Jest 28

Jest 为 ECMAScript 模块 (ESM) 提供了一些实验性支持,但“node_modules”尚未被 next/jest 转译

所以我们需要使用来transformIgnorePatterns防止ESM文件被转换。

更改的默认配置transformIgnorePatterns将被覆盖,请next/jest参阅下面的解决方案。

// 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 () => ({
  ...(await createJestConfig(customJestConfig)()),
  transformIgnorePatterns: [
    // The regex below is just a guess, you might tweak it
    'node_modules/(?!(react-markdown|rehype-raw|remark-gfm)/)',
  ]
})
Run Code Online (Sandbox Code Playgroud)

我创建了一个存储库,以完整参考正在使用的案例的必要设置swiper/reacthttps://github.com/markcnunes/with-jest-and-esm

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

如果您正在寻找与swiper/react.