这是我要测试的组件
页脚/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;
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/