我对此做了大量的研究,并找到了相当多的解决方案。我已经找到了一种类似于解决方案的方法,并希望transform和transformIgnorePatterns能够正常工作。不过,似乎我唯一能做到的就是在我的__mocks__文件夹中手动添加一些模拟模块。
不确定这是否是由于在Nextjs中使用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);我已经读到我也需要一个babel.config.js。这是那个文件:
module.exports = {
presets: ["next/babel", "@babel/preset-env"],
};发布于 2022-07-10 07:12:11
这里有一个解决方案,以防有人遇到同样的问题,但正在使用NextJs 12.2、next/jest和Jest 28。
Jest为ECMAScript模块提供了一些实验支持但是模块“还没有转移到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)/)',
]
})我创建了一个存储库,用于完全引用正在使用swiper/react的一个案例所需的设置。https://github.com/markcnunes/with-jest-and-esm
请记住,对于未来的Next.js / next/js版本,此设置可能需要更改,但只是共享此方法,以防此方法对使用此设置的其他人有用。
我还对另一个问题使用了这个答案,以防您正在寻找与swiper/react相关的解决方案。
https://stackoverflow.com/questions/71427330
复制相似问题