解決jest處理es模塊


解決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去處理了

  1. 安裝依賴

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

  2. 配置babel.config.js

    module.exports = {
        presets: [
            [
                "@babel/preset-env",
                {
                    targets: {
                        node: "current"
                    }
                }
            ]
        ],
        plugins: ["transform-es2015-modules-commonjs"]
    };
    
    
  3. 配置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))"]
    };
    
    

    腳注


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM