相关疑问
什么是单元测试?
为什么要进行单元测试?
单元测试怎么进行?
单元测试效果验收?
问答上面的问题
文档内容参考链接
https://www.liaoxuefeng.com/wiki/897692888725344/953546675792640
https://www.zhihu.com/question/28729261
单元测试
安装依赖
配置文件
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 版本也不对
修改

[Vue warn]: Property "$ELEMENT" was accessed during render but is not defined on instance.
属性"$ELEMENT"在渲染期间被访问,但没有在实例上定义。