NextJS应用运行Jest测试无法解析SVG图片的问题及解决
NextJS运行Jest测试提示无法解析非纯JavaScript文件报错解决方案
报错现象
运行yarn test执行测试时Jest抛出如下错误:
Jest encountered an unexpected token This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript. By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules". Here's what you can do: • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it. • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config. • If you need a custom transformation specify a "transform" option in your config. • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option. You'll find more details and examples of these config options in the docs: https://jestjs.io/docs/en/configuration.html Details: /home/marouane/projects/manage-landing-page/jest.setup.ts:1 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import "@testing-library/jest-dom/extend-expect"; ^^^^^^ SyntaxError: Cannot use import statement outside a module at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
核心报错点为SyntaxError: Cannot use import statement outside a module,错误出现在.ts后缀的jest配置启动文件中。
已尝试的操作
安装jest-svg-transformer依赖,并添加了如下jest.config.js配置:
module.exports = { setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"], transform: { '^.+\.jsx?$': 'babel-jest', '^.+\.svg$': 'jest-svg-transformer', }, };
配置后问题未解决。
根因与修复方案
报错原因是transform配置的匹配规则书写错误:原规则^.+\.jsx?$仅匹配.js、.jsx后缀的文件,未覆盖项目中使用的.ts、.tsx后缀文件,导致TypeScript文件没有被正确转译,ESModule的import语法无法被识别。
将匹配规则修改为^.+\.tsx?$即可覆盖所有TS/TSX文件,修复后完整配置如下:
module.exports = { setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"], transform: { '^.+\.tsx?$': 'babel-jest', '^.+\.svg$': 'jest-svg-transformer', }, };
如果项目同时存在JS和TS文件,可以将规则合并为^.+\.[jt]sx?$,同时匹配两类后缀的文件。
内容的提问来源于stack exchange,提问作者Marsou001
相关产品推荐
相关产品推荐

