zoukankan      html  css  js  c++  java
  • 解决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))"]
      };
      
      

      脚注

  • 相关阅读:
    精简版的MySQL制作步骤
    WCF中常用的binding方式 z
    SQLite的.NET应用自适应32位/64位系统 z
    DEV GridControl 常用属性 z
    SpringBoot项目设置热部署
    SpringBoot整合Quartz定时任务
    单引号、双引号 转义符
    Java几种常见的四舍五入的方法
    Java集合之保持compareTo和equals同步
    你真的了解try{ return }finally{}中的return?(转载)
  • 原文地址:https://www.cnblogs.com/xueyoucd/p/10495922.html
Copyright © 2011-2022 走看看