解决jest处理es模块示例详解
问题场景
项目使用jest进行测试时, 当引入外部库是es模块时, jest无法处理导致报错.
Test suite failed to run
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:
• 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.
Details:
/home/xueyou/workspace/projects/node_modules/lodash-es/lodash.js:10
import * as lodash from 'lodash-es'
SyntaxError: Unexpected token *
解决方法
查阅issues发现, 目前jest不支持em模块, 只有通过babel去处理了
安装依赖
yarn add --dev babel-jest @babel/core @babel/preset-env babel-plugin-transform-es2015-modules-commonjs
配置babel.config.js
module.exports = {
presets: [
[
"@babel/preset-env",
{
targets: {
node: "current"
}
}
]
],
plugins: ["transform-es2015-modules-commonjs"]
};
配置jest.config.js
module.exports = {
preset: "ts-jest",
testMatch: ["<rootDir>/tests/**/*.(spec|test).ts?(x)"],
transform: {
// 将.js后缀的文件使用babel-jest处理
"^.+\\.js$": "babel-jest",
"^.+\\.(ts|tsx)$": "ts-jest"
},
// 下面非要从重要, 将不忽略 lodash-es, other-es-lib 这些es库, 从而使babel-jest去处理它们
transformIgnorePatterns: ["<rootDir>/node_modules/(?!(lodash-es|other-es-lib))"]
};
脚注
以上就是解决jest处理es模块示例详解的详细内容,更多关于解决jest处理es模块的资料请关注脚本之家其它相关文章!
相关文章
Vite+React+TypeScript手撸TodoList的项目实践
本文主要介绍了Vite+React+TypeScript手撸TodoList的项目实践,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2022-05-05
基于Cloud Studio构建React完成点餐H5页面(腾讯云 Cloud Studio 实战训练营)
最近也是有机会参与到了腾讯云举办的腾讯云Cloud Studio实战训练营,借此了解了腾讯云Cloud Studio产品,下面就来使用腾讯云Cloud Studio做一个实战案例来深入了解该产品的优越性吧,感兴趣的朋友跟随小编一起看看吧2023-08-08
react 路由权限动态菜单方案配置react-router-auth-plus
这篇文章主要为大家介绍了react路由权限动态菜单方案react-router-auth-plus傻瓜式配置详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-08-08
react中使用Modal.confirm数据不更新的问题完美解决方案
这篇文章主要介绍了react中使用Modal.confirm数据不更新的问题解决方案,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-09-09


最新评论