【问题标题】:Why am I unable to import SVG in Jest?为什么我无法在 Jest 中导入 SVG?
【发布时间】:2022-02-04 22:50:36
【问题描述】:

这是我要测试的组件

页脚/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 运行测试时,它显示错误

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,但还是不行

【问题讨论】:

    标签: javascript reactjs svg jestjs enzyme


    【解决方案1】:
    • 安装 camelcase 包 (npm install -D camelcase) (yarn add -D camelcase)
    • 在您的 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',
      },
      

    【讨论】:

    猜你喜欢
    • 2016-10-09
    • 1970-01-01
    • 2021-12-11
    • 2021-07-05
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 2018-11-30
    • 1970-01-01
    相关资源
    最近更新 更多