用Jest测试单文件组件
1、安装 Jest 和 Vue Test Utils
npm install --save-dev jest @vue/test-utils
2、安装和配置 vue-jest 预处理器
npm install --save-dev vue-jest
3、配置相关文件
(1)package.json
// package.json { "scripts": { "test": "jest" } }
(2)jsconfig.js
{ "compilerOptions": { "baseUrl": "./", "paths": { "@/*": ["src/*"] } }, "exclude": ["node_modules", "dist"] }
(3)babel.config.js
module.exports = { presets: [ '@vue/cli-plugin-babel/preset', '@babel/preset-env', { targets: { node: 'current' } } ], plugins: ['transform-es2015-modules-commonjs'] }
(4)jest.config.js
module.exports = { 'verbose': true, 'moduleFileExtensions': [ 'js', 'json', 'vue' ], 'transform': { '.*\\.(vue)$': 'vue-jest', '^.+\\.js$': '<rootDir>/node_modules/babel-jest' }, 'moduleNameMapper': { '^@/(.*)$': '<rootDir>/src/$1' } }
4、解决babel解析es6出错问题,配置安装 @babel/preset-env
npm install --save-dev @babel/preset-env
检查babel.config.js配置是否与上面相同。
如果配置没错但系统仍报错,检查package.json,将babel-core模块的版本设置为"^7.0.0-0",重新npm install
5、开始测试
(1)新建HelloWorld.vue
<template> <div> <span class="count">{{ count }}</span> <button @click="increment">Increment</button> <button id="subtract" @click="subtract">subtract</button> </div> </template> <script> export default { data () { return { count: 1 } }, methods: { increment () { this.count++ }, subtract () { this.count-- } } } </script>
(2)新建test.js
/** * @jest-environment jsdom */ import { mount } from '@vue/test-utils' import HelloWorld from '@/components/HelloWorld.vue' describe('HelloWorld', () => { // Now mount the component and you have the wrapper const wrapper = mount(HelloWorld) it('renders the correct markup', () => { expect(wrapper.html()).toContain('<span class="count">1</span>') }) //it's also easy to check for the existence of elements it('has a button', () => { expect(wrapper.contains('button')).toBe(true) }) it('button should increment the count', () => { expect(wrapper.vm.count).toBe(1) const button = wrapper.find('button') button.trigger('click') expect(wrapper.vm.count).toBe(2) }) it('button should subtract the count', () => { expect(wrapper.vm.count).toBe(2) const button = wrapper.find('#subtract') button.trigger('click') expect(wrapper.vm.count).toBe(1) }) })
(3)运行测试文件
a.直接点击下图红框处运行单文件
b.使用npm run test执行所有测试文件
(4)测试结果(通过)
6、报错解决
(1)环境错误
a.错误信息
Test suite failed to run
[vue-test-utils]: window is undefined, vue-test-utils needs to be run in a browser environment.
You can run the tests in node using jsdom
See https://vue-test-utils.vuejs.org/guides/#browser-environment for more details.
b.解决方案
在测试文件最上方添加代码
/** * @jest-environment jsdom */
(2)无法识别element组件
a.错误信息
Unknown custom element: - did you register the component correctly? For recursive components……
b.解决方法
import ElementUI from 'element-ui' import VueRouter from 'vue-router' // 创建临时Vue实例,挂载组件中使用的插件 const localVue = createLocalVue() localVue.use(ElementUI) localVue.use(VueRouter) const router = new VueRouter() ……………… const wrapper = mount(statisticalOverview, { localVue, router }) ………………