In my Next.js 12.1.4 project, I am using Typescript, React Testing Library, and SVGR for importing icons like this:
import ChevronLeftIcon from './chevron-left.svg'
The issue arises when running a test on a component that includes an SVG import, leading to the following error:
console.error
Warning: React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.
Check the render method of `Loader`.
at Loader (.../src/components/atoms/Loader/Loader.tsx:11:36)
at div
at button
at Button (.../src/components/atoms/buttons/Button/Button.tsx:19:5)
15 | }`}
16 | >
> 17 | <LoaderIcon />
| ^
18 | </div>
19 | )
20 |
at printWarning (node_modules/react/cjs/react-jsx-runtime.development.js:117:30)
at error (node_modules/react/cjs/react-jsx-runtime.development.js:93:5)
at jsxWithValidation (node_modules/react/cjs/react-jsx-runtime.development.js:1152:7)
at Object.jsxWithValidationDynamic [as jsx] (node_modules/react/cjs/react-jsx-runtime.development.js:1209:12)
at Loader (src/components/atoms/Loader/Loader.tsx:17:23)
at renderWithHooks (node_modules/react-dom/cjs/react-dom.development.js:14985:18)
at mountIndeterminateComponent (node_modules/react-dom/cjs/react-dom.development.js:17811:13)
My tests are executed with yarn test
, specified in the following script
within my package.json
:
"test": "TZ=UTC ./node_modules/jest/bin/jest.js",
This is what I have configured in next.config.js
for SVGR:
webpack(config) {
config.module.rules.push({
test: /\.svg$/,
use: ['@svgr/webpack'],
})
return config
},
Here is my jest.config.js setup:
const nextJest = require('next/jest')
const createJestConfig = nextJest({
dir: './',
})
const customJestConfig = {
moduleDirectories: ['node_modules', '<rootDir>/src/'],
testEnvironment: 'jest-environment-jsdom',
moduleNameMapper: {
'\\.svg$': '<rootDir>/src/__mocks__/svgrMock.tsx',
},
}
module.exports = createJestConfig(customJestConfig)
and src/__mocks__/svgrMock.tsx
:
import React, { SVGProps } from 'react'
const SvgrMock = React.forwardRef<SVGSVGElement, SVGProps<SVGSVGElement>>(
(props, ref) => <svg ref={ref} {...props} />,
)
SvgrMock.displayName = 'SvgrMock'
export const ReactComponent = SvgrMock
export default SvgrMock
I also attempted to utilize jest-svg-transformer
without significant improvement.
These are the versions of the libraries being used:
- "next": "^12.1.4"
- "react": "17.0.2"
- "react-dom": "17.0.2"
- "@svgr/webpack": "^5.5.0"
- "@testing-library/jest-dom": "^5.16.4"
- "@testing-library/react": "^12.1.4"
- "@testing-library/user-event": "^14.0.4"
- "jest": "^27.5.1"
- "ts-jest": "^27.1.3"
- "typescript": "4.4.4"
Your assistance is greatly appreciated :)