单元测试相关疑问、单元测试、错误调试记录

相关疑问

什么是单元测试?

为什么要进行单元测试?

单元测试怎么进行?

单元测试效果验收?

问答上面的问题

文档内容参考链接

https://www.liaoxuefeng.com/wiki/897692888725344/953546675792640

https://www.zhihu.com/question/28729261

单元测试

安装依赖

yarn add jest
yarn add vue-jest@5.0.0-alpha.5
yarn add babel-jest
yarn add @vue/compiler-sfc@3.0.2
yarn add @vue/test-utils@next  
yarn add typescript

配置文件

jest.config.js

module.exports = {
testEnvironment: 'jsdom', // 默认JSdom
roots: [
'<rootDir>/src',
'<rootDir>/packages',
 ], //
transform: {
'^.+\\.vue$': 'vue-jest', // vue单⽂件
'^.+\\js$': 'babel-jest' // esm最新语法 import
 },
moduleFileExtensions: ['vue', 'js', 'json', 'jsx', 'ts', 'tsx', 'node'],
testMatch: ['**/__tests__/**/*.spec.js'],
// 别名
moduleNameMapper: {
'^element-ui(.*)$': '<rootDir>$1',
'^main(.*)$': '<rootDir>/src$1'
 }
}

测试文件 

/packages/button/tests/Button.spec.js

import Button from "../Button.vue";
import { mount } from "@vue/test-utils";

//模拟运行组件
it("content", () => {
  const Comp = {
  template: `<div><Button>默认按钮</Button></div>`,
 };

const wrapper = mount(Comp, {
  global: {
    components: {
      Button,
    },
  },
 });

 //断言
expect(wrapper.findComponent({ name: "ElButton" }).text()).toContain("默认按钮");

});

测试

配置 package.json

"test": "jest --runInBand", # 序列化执⾏

"scripts": {
    "test": "jest --runInBand"
  },

 运行

npm run jest

错误调试记录

错误 1:no tests found

错误原因

__tests__ 文件夹命名错误,少些了s。

错误 2:Cannot destructure property 'config'

TypeError: Cannot destructure property 'config' of 'undefined' as it is undefined.

      at Object.getCacheKey (node_modules/vue-jest/lib/index.js:10:7)

网上查了类似的错误,说是 jest 的版本问题。

参考

https://segmentfault.com/a/1190000040202502

原来用的 

yarn add jest

"jest": "^27.0.4"

重装 jest 

yarn add jest@26.6.3

"jest": "26.6.3" 

错误3:babelJest.getCacheKey is not a function

Test suite failed to run

    TypeError: babelJest.getCacheKey is not a function

错误原因:jest 相关资源 babel-jest 版本也不对

修改

yarn add babel-jest@26.3.0
修改后再测试就好了。

[Vue warn]: Property "$ELEMENT" was accessed during render but is not defined on instance.

属性"$ELEMENT"在渲染期间被访问,但没有在实例上定义。

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Irene1991

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值