玩笑 - 使用转换属性时遇到意外标记

CCC*_*CCC 5 javascript testing unit-testing reactjs jestjs

我无法在测试中导入 Svg,因此我按照此处的答案进行操作。

\n

我已将此添加到jest.config.js

\n
"transform": {\n   ...\n   "^.+\\\\.svg$": "jest-svg-transformer"\n}\n
Run Code Online (Sandbox Code Playgroud)\n

添加后,出现错误:

\n
Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.\n\n    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.\n\n    By default "node_modules" folder is ignored by transformers.\n\n    Here\'s what you can do:\n     \xe2\x80\xa2 If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.\n     \xe2\x80\xa2 If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript\n     \xe2\x80\xa2 To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.\n     \xe2\x80\xa2 If you need a custom transformation specify a "transform" option in your config.\n     \xe2\x80\xa2 If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.\n\n    You\'ll find more details and examples of these config options in the docs:\n    https://jestjs.io/docs/configuration\n    For information about custom transformations, see:\n    https://jestjs.io/docs/code-transformation\n\n    Details:\n\n    /Users/CCCC/Desktop/SourceTree/my-proj/src/setupTests.js:1\n    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { configure } from "enzyme";\n                                                                                      ^^^^^^\n\n    SyntaxError: Cannot use import statement outside a module\n\n      at Runtime.createScriptFromCode (node_modules/@jest/core/node_modules/jest-runtime/build/index.js:1728:14)\n
Run Code Online (Sandbox Code Playgroud)\n

有人知道为什么失败吗?

\n

笑话配置.js

\n
module.exports = {\n  moduleDirectories: ["node_modules", "src"],\n  moduleNameMapper: {\n    "^@/(.*)$": "<rootDir>/src/$1",\n    "\\\\.(css|scss)$": "identity-obj-proxy",\n  },\n  transform: {\n    "^.+\\\\.svg$": "<rootDir>/src/svgTransform.js",\n  },\n  setupFilesAfterEnv: ["<rootDir>/src/setupTests.js"],\n  snapshotSerializers: ["enzyme-to-json/serializer"],\n};\n
Run Code Online (Sandbox Code Playgroud)\n

setupTest.js

\n
import { configure } from "enzyme";\nimport Adapter from "enzyme-adapter-react-16";\n\nconfigure({ adapter: new Adapter() });\n
Run Code Online (Sandbox Code Playgroud)\n

CCC*_*CCC 5

我安装babel-jest并使用它后transform,它可以工作。

    "transform": {
      "^.+\\.js$": "babel-jest", // added this line
      ...
    }
Run Code Online (Sandbox Code Playgroud)

参考:
如何解决 jest 中的“无法在模块外部使用 import 语句”