簡體   English   中英

React.jsx:使用 Jest 和 React 測試庫測試帶有 svg 的 React 組件時類型無效

[英]React.jsx: type is invalid when testing a React component with an svg with Jest and React Testing Library

我有一個 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)

我使用yarn test運行測試,它與我的package.json中的以下script相匹配: "test": "TZ=UTC./node_modules/jest/bin/jest.js",

這是我在next.config.js的 next.config.js 中的內容:

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

    return config
},

這是我的 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)

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

我也嘗試使用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/user-event": "^14.0.4"
  • “開玩笑”:“^27.5.1”
  • “ts-笑話”:“^27.1.3”
  • “打字稿”:“4.4.4”

謝謝你的幫助:)

經過幾天的試驗和錯誤后,我能夠通過使用Next.js文檔中的 Jest 和 Babel 配置來解決這個問題,而不是使用由 Rust 編譯器提供支持的next/jest插件: https://nextjs.org/文檔/測試#setting-up-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}
            `
  },
}

jest.config.js

  • moduleNameMapper中:從 '^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp)$/i' 中刪除svg '^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp)$/i': '<rootDir>/<path to your mock files (eg) __mocks__>/fileMock.js',
  • transform中:添加'^.+\\.svg$': '<rootDir>/<path to your mock files (eg) __mocks__>/jestSvgTransformer.js'
  • 添加moduleDirectories: ['node_modules', 'src'],以啟用絕對導入

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM