解決jest處理es模塊示例詳解
問(wèn)題場(chǎng)景
項(xiàng)目使用jest進(jìn)行測(cè)試時(shí), 當(dāng)引入外部庫(kù)是es模塊時(shí), jest無(wú)法處理導(dǎo)致報(bào)錯(cuò).
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模塊, 只有通過(guò)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庫(kù), 從而使babel-jest去處理它們
transformIgnorePatterns: ["<rootDir>/node_modules/(?!(lodash-es|other-es-lib))"]
};
腳注
以上就是解決jest處理es模塊示例詳解的詳細(xì)內(nèi)容,更多關(guān)于解決jest處理es模塊的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
react如何實(shí)現(xiàn)一個(gè)密碼強(qiáng)度檢測(cè)器詳解
這篇文章主要給大家介紹了關(guān)于react如何實(shí)現(xiàn)一個(gè)密碼強(qiáng)度檢測(cè)器的相關(guān)資料,使用這個(gè)密碼強(qiáng)度器后可以幫助大家提高在線帳號(hào)、個(gè)人信息的安全性,需要的朋友可以參考下2021-06-06
React實(shí)現(xiàn)核心Diff算法的示例代碼
這篇文章主要為大家詳細(xì)介紹了React如何實(shí)現(xiàn)Diff算法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2022-04-04
用React-Native+Mobx做一個(gè)迷你水果商城APP(附源碼)
這篇文章主要介紹了用React-Native+Mobx做一個(gè)迷你水果商城APP,功能需要的朋友可以參考下2017-12-12
在react-router4中進(jìn)行代碼拆分的方法(基于webpack)
這篇文章主要介紹了在react-router4中進(jìn)行代碼拆分的方法(基于webpack),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-03-03
React中常見(jiàn)的TypeScript定義實(shí)戰(zhàn)教程
這篇文章主要介紹了React中常見(jiàn)的TypeScript定義實(shí)戰(zhàn),本文介紹了Fiber結(jié)構(gòu),F(xiàn)iber的生成過(guò)程,調(diào)和過(guò)程,以及 render 和 commit 兩大階段,需要的朋友可以參考下2022-10-10
react-redux action傳參及多個(gè)state處理的實(shí)現(xiàn)
本文主要介紹了react-redux action傳參及多個(gè)state處理的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
React hook 'useState' is calle
這篇文章主要為大家介紹了React hook 'useState' is called conditionally報(bào)錯(cuò)解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12

