解決jest處理es模塊示例詳解
問題場景
項目使用jest進(jìn)行測試時, 當(dāng)引入外部庫是es模塊時, jest無法處理導(dǎo)致報錯.
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發(fā)現(xiàn), 目前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模塊示例詳解的詳細(xì)內(nèi)容,更多關(guān)于解決jest處理es模塊的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
用React-Native+Mobx做一個迷你水果商城APP(附源碼)
這篇文章主要介紹了用React-Native+Mobx做一個迷你水果商城APP,功能需要的朋友可以參考下2017-12-12
在react-router4中進(jìn)行代碼拆分的方法(基于webpack)
這篇文章主要介紹了在react-router4中進(jìn)行代碼拆分的方法(基于webpack),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03
React中常見的TypeScript定義實戰(zhàn)教程
這篇文章主要介紹了React中常見的TypeScript定義實戰(zhàn),本文介紹了Fiber結(jié)構(gòu),F(xiàn)iber的生成過程,調(diào)和過程,以及 render 和 commit 兩大階段,需要的朋友可以參考下2022-10-10
react-redux action傳參及多個state處理的實現(xiàn)
本文主要介紹了react-redux action傳參及多個state處理的實現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
React hook 'useState' is calle
這篇文章主要為大家介紹了React hook 'useState' is called conditionally報錯解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12

