Continued from nextjs 14 + svgr + jest " Warning: React.jsx: type is invalid -- expected a string or a class/functionbut got: object." An error appears #58948
-
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 6 replies
-
Hi, The thing is that, the Next.js Jest Config, has already an // pseudo-code
moduleNameMapper: {
'regex-that-matches-svg-by-next.js': /* code */,
...yourCustomConfig.moduleNameMapper,
} You can see that your matcher would go "after" the Next.js SVG matcher. That means that if you knew the actual matcher used by Next.js, you could override it, object spreading normally does const yourCustomConfig = {
moduleNameMapper: {
'regex-that-matches-svg-by-next.js': /* code */,
}
} Then when these get merged, yours would be last, and hence, it would be the key used when matching SVG files. const foo = { a: 0 }
const bar = { a: 100, ...foo }
bar.a // 0; You can see where this is going, when a file is to be matched, we go through the keys in the matcher, and which ever matches first, is used. Since there's a Next.js matcher first, that'll win over yours, unless you override it, or place yourself above it... Trying to override it, is brittle, because as soon as there's a change to it, your tests would start to break. So what if instead, we make sure our custom matcher is always first... const nextJest = require("next/jest");
const createJestConfig = nextJest({
dir: "./",
});
/** @type {import('jest').Config} */
const customJestConfig = {
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
moduleNameMapper: {
"^@/(.*)$": "<rootDir>/src/$1",
},
testEnvironment: "jest-environment-jsdom",
};
const jestConfigWithOverrides = async (...args) => {
const configFn = createJestConfig(customJestConfig);
const res = await configFn(...args);
res.moduleNameMapper = {
// we cannot depend on the exact key used by Next.js
// so we inject an SVG key higher up on the mapping tree
"\\.svg": "<rootDir>/src/__mocks__/svgrMock.js",
...res.moduleNameMapper,
};
return res;
};
module.exports = jestConfigWithOverrides;
|
Beta Was this translation helpful? Give feedback.
No worries! Please don't forget to mark as answered!