React.jsx:使用 Jest 和 React 测试库使用 svg 测试 React 组件时,类型无效

Den*_*nis 2 svg typescript jestjs next.js

我有一个 Next.js 12.1.4 项目,使用 Typescript、React 测试库和 SVGR 来导入如下图标:import ChevronLeftIcon from './chevron-left.svg'

我遇到的问题是,当我运行包含 SVG 导入的组件测试时,出现以下错误:

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)
Run Code Online (Sandbox Code Playgroud)

我运行的测试与我的yarn test以下内容相匹配: scriptpackage.json"test": "TZ=UTC ./node_modules/jest/bin/jest.js",

这是我对 SVGR 的了解next.config.js

webpack(config) {
    config.module.rules.push({
        test: /\.svg$/,
        use: ['@svgr/webpack'],
    })

    return config
},
Run Code Online (Sandbox Code Playgroud)

这是我的 jest.config.js:

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)
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

我也尝试使用jest-svg-transformer但没有太大成功。

以下是涉及的库的版本:

  • “下一个”:“^12.1.4”
  • “反应”:“17.0.2”
  • “反应-dom”:“17.0.2”
  • "@svgr/webpack": "^5.5.0"
  • "@testing-library/jest-dom": "^5.16.4"
  • “@testing-library/react”:“^12.1.4”
  • “@testing-library/用户事件”:“^14.0.4”
  • “笑话”:“^27.5.1”
  • "ts-jest": "^27.1.3"
  • “打字稿”:“4.4.4”

感谢您的帮助 :)

Den*_*nis 5

经过几天的试验和错误,我能够通过使用文档中的 Jest 和 Babel 配置来解决这个问题Next.js,而不是使用next/jestRust 编译器支持的插件: https: //nextjs.org/docs/testing#设置 jest-with-babel

我还必须为 svg 文件定义一个笑话转换器jestSvgTransformer.js

const path = require('path')

module.exports = {
  process(src, filePath) {
    if (path.extname(filePath) !== '.svg') {
      return src
    }

    const name = `svg-${path.basename(filePath, '.svg')}`
      .split(/\W+/)
      .map((x) => `${x.charAt(0).toUpperCase()}${x.slice(1)}`)
      .join('')

    return `
const React = require('react');
function ${name}(props) {
  return React.createElement(
    'svg',
    Object.assign({}, props, {'data-file-name': ${name}.name})
  )
}
module.exports = ${name}
            `
  },
}
Run Code Online (Sandbox Code Playgroud)

jest.config.js

  • moduleNameMappersvg'^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp)$/i': '<rootDir>/<path to your mock files (e.g.) __mocks__>/fileMock.js',
  • transform:添加'^.+\\.svg$': '<rootDir>/<path to your mock files (e.g.) __mocks__>/jestSvgTransformer.js'
  • 添加moduleDirectories: ['node_modules', 'src'],以启用绝对导入