日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

解決jest處理es模塊示例詳解_React

作者:xueyou2000 ? 更新時(shí)間: 2023-04-07 編程語(yǔ)言

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

腳注

  • Unexpected import inside nodejs module
  • Unexpected Token Import for ES6 modules

原文鏈接:https://www.cnblogs.com/xueyoucd/p/10495922.html

欄目分類
最近更新