javascript - 为什么我无法在 Jest 中导入 SVG?

标签 javascript reactjs svg jestjs enzyme

这是我要测试的组件

页脚/index.jsx

import React from "react";

import logoImg from "@/assets/images/components/header/logo-header.svg";
import HeaderTextImg from "@/assets/images/components/header/header-text.svg";

function Footer() {
  return (
    <div>Footer</div>
  );
}

export default Footer;

当我通过npm run test运行测试时,它显示错误
enter image description here enter image description here

package.json

 "scripts": {
    "test": "jest --watchAll",
    "test-coverage": "jest --coverage", 
  },
  "jest": {
    "moduleDirectories": [
      "node_modules",
      "src"
    ],
    "moduleNameMapper": {
      "\\.(css|scss)$": "identity-obj-proxy"
    },
    "setupFilesAfterEnv": [
      "<rootDir>/src/setupTests.js"
    ],
    "snapshotSerializers": [
      "enzyme-to-json/serializer"
    ]
  }

我尝试过的
我尝试在 package.json 中使用 jest-svg-transformer ,如下所示:

        "transform": {
            "^.+\\.jsx?$": "babel-jest",
            "^.+\\.svg$": "jest-svg-transformer"
        }

它也显示错误:

    ● Invalid transformer module:
      "/Users/CCCC/Desktop/SourceTree/my-proj/node_modules/jest-svg-transformer/lib/index.js" specified in the "transform" object of Jest configuration
      must export a `process` or `processAsync` or `createTransformer` function.
      Code Transformation Documentation:
      https://jestjs.io/docs/code-transformation

更新 1
我也尝试过

moduleNameMapper: {
    "^.+\\.svg$": "jest-svg-transformer",
}

但也不起作用

更新2
尝试过svg-jest也一样,但还是不行

最佳答案

  • 安装camelcase包(npm install -Dcamelcase)(yarnadd-Dcamelcase)
  • 在 jest 目录中创建 fileTransform.js 文件

/jest/transforms/fileTransform.js

const path = require('path');
const camelcase = require('camelcase');

module.exports = {
    process(src, filename) {
        const assetFilename = JSON.stringify(path.basename(filename));
    if (filename.match(/\.svg$/)) {
        // Based on how SVGR generates a component name:
        // https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6
        const pascalCaseFilename = camelcase(path.parse(filename).name, {
            pascalCase: true,
        });
        const componentName = `Svg${pascalCaseFilename}`;
        return `const React = require('react');
  module.exports = {
    __esModule: true,
    default: ${assetFilename},
    ReactComponent: React.forwardRef(function ${componentName}(props, ref) {
      return {
        $$typeof: Symbol.for('react.element'),
        type: 'svg',
        ref: ref,
        key: null,
        props: Object.assign({}, props, {
          children: ${assetFilename}
        })
      };
    }),
  };`;
    }

    return `module.exports = ${assetFilename};`;
},
};
  • 在 package.json 中添加以下内容:

    transform: {
           '^(?!.*\\.(js|jsx|mjs|cjs|ts|tsx|css|json)$)': '<rootDir>/jest/transforms/fileTransform.js',
    },
    

关于javascript - 为什么我无法在 Jest 中导入 SVG?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70985625/

相关文章:

svg - 是否可以使用路径绘制的内联 svg 来掩盖图像?

javascript - 单击在测试完成中使用变量不起作用

javascript - 执行不同组件的功能

javascript - this 在 render() 中的一个函数中

javascript - 在谷歌地图 react 的标记上添加工具提示

javascript - 条件渲染 react 问题

reactjs - 手动设置电流时,我使用什么 typescript 类型与 useRef() Hook ?

javascript - Angular ui-router 解析中的动态依赖注入(inject)

firefox - 动画 SVG 在 Firefox 中不起作用,在 Chrome 中有效

jquery - 如何使用CSS3、HTML5、SVG、Jquery制作不规则曲线?