安装最新 Jest 报错:TypeError: Cannot read property ‘instrument‘ of undefined

背景:

为了在已有的项目中加入 Jest ,踩了不少坑,坑列举如下,采用过的解决方式,出现的新问题,最终的处理手段。

首先,我的项目是 Vue2,package.json 的 babel 为 @babel,因此才会出现以下种种问题,该版本的处理方式是,不用管 babel 的版本问题,而是采用 CLI 插件 去启动 jest;若为 babel 版本,正常 npm install -g jest 配置脚本即可,后面会有说明;Vue3 的 Jest 安装更为简单,本篇不涉及。

坑1: 直接在 Vue 项目中运行,报错

requires Babel "^7.0.0-0", but was loaded with "6.26.3". If you are sure you have a compatible version of @babel/core, it is likely that something in your build process is loading the wrong version. Inspect the stack trace of this error to look for the first entry that doesn't mention "@babel/core" or "babel-core" to see what is calling Babe

试过:

npm install --save-dev "babel-core@^7.0.0-bridge.0"

还安装了各种@babel 或 babel

但都没有起作用。猜测是 Jest 自带的包导致的冲突。

坑2: 那么把 Jest 升级到最新版吧,27+。报错

TypeError: Cannot read property 'instrument' of undefined

咋办呢?网上好像找不出好方法了,那么去 github 上,看看大佬们 @babel + Vue2 + Jest 能跑得起来的项目吧,这里给出了最小的安装项。

解决方法

npm install @vue/test-utils -D
npm install @vue/cli-service -D
npm install @vue/cli-plugin-unit-jest -D

jest.conf.js 放在根目录下,或 tests 目录下,或任何你想放的

module.exports = {
  preset: '@vue/cli-plugin-unit-jest',
  collectCoverage: false
}

package.json 配置脚本和配置文件目录

"scripts": {
   "test:unit": "vue-cli-service test:unit --config ./tests/jest.conf.js",
}

如果你报错了:
在这里插入图片描述
解决:报错信息说明。路径不匹配,找不到测试文件,因此把目录改成 tests/unit 即可。

报错
在这里插入图片描述
解决:由报错信息可知,vue-template-compiler 和 vue 需为同一个版本,因此安装 vue-template-compiler 对应的 vue 版本即可。我的是 npm install vue-template-compiler@2.6.10

至此单元测试就跑起来了,老激动了。
在这里插入图片描述
补充:

我的项目没有改动过.babelrc 文件,就可以跑起来了
在这里插入图片描述
我的 package.json:
在这里插入图片描述

这里讲讲,为 babel 版本的 Jest 安装和配置,先看看部分的 package.json
在这里插入图片描述在这里插入图片描述

简单启动一个项目
在这里插入图片描述
安装 Jest
全局:npm install -g jest 或局部: npm install -D jest
在 package.json 中指定 test 脚本:
在这里插入图片描述
运行脚本即可测试。

最后的最后,若是 TS,则需额外安装其他的包和额外进行配置,网上找不到就去看看 github 吧。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值