iis服务器助手广告广告
返回顶部
首页 > 资讯 > 前端开发 > JavaScript >解决jest处理es模块示例详解
  • 645
分享到

解决jest处理es模块示例详解

解决jest处理es模块jest处理es模块 2023-02-06 12:02:29 645人浏览 薄情痞子
摘要

目录问题场景解决方法问题场景 项目使用jest进行测试时, 当引入外部库是es模块时, jest无法处理导致报错. Test suite failed to run

问题场景

项目使用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去处理了

安装依赖

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库, 从而使babel-jest去处理它们
    transformIgnorePatterns: ["<rootDir>/node_modules/(?!(lodash-es|other-es-lib))"]
};

脚注

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

以上就是解决jest处理es模块示例详解的详细内容,更多关于解决jest处理es模块的资料请关注编程网其它相关文章!

--结束END--

本文标题: 解决jest处理es模块示例详解

本文链接: https://www.lsjlt.com/news/194301.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作