解決jest處理es模塊

解決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

  1. 安裝依賴node

    yarn add --dev babel-jest @babel/core @babel/preset-env babel-plugin-transform-es2015-modules-commonjsgit

  2. 配置babel.config.jsgithub

    module.exports = {
        presets: [
            [
                "@babel/preset-env",
                {
                    targets: {
                        node: "current"
                    }
                }
            ]
        ],
        plugins: ["transform-es2015-modules-commonjs"]
    };
  3. 配置jest.config.jsbabel

    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))"]
    };

    腳註

相關文章
相關標籤/搜索