解決jest處理es模塊
問題場景
項目使用jest
進行測試時, 當引入外部庫是es
模塊時, jest
沒法處理致使報錯.javascript
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
去處理了java
-
安裝依賴node
yarn add --dev babel-jest @babel/core @babel/preset-env babel-plugin-transform-es2015-modules-commonjs
git -
配置
babel.config.js
githubmodule.exports = { presets: [ [ "@babel/preset-env", { targets: { node: "current" } } ] ], plugins: ["transform-es2015-modules-commonjs"] };
-
配置
jest.config.js
babelmodule.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))"] };
腳註