前面介绍过使用vue cli单元测试。如果你读过这篇文章,你会深深感觉到使用vue cli写单元测试不是很方便,比如测试事件时不得不派发自定义事件。另一方面,jest对React测试的支持在好很多,老早就可以专门的API处理事件了,谁让它们都有一个Facebook亲爹呢。技术是进步的,一天在vue官网瞎逛,偶然它们发现已经推出了Vue Test Utils,虽然只是vuev1.0.0-beta.19,但也提供了强大的API,写单元测试就更溜了。赶紧Git下来试一下。
Vue Test Utils是Vue.js官方的单元测试实用工具库。Vue单文件组件在它们运行于Node或浏览器之前是需要预编译的。对于Node环境推荐通过Jest预编译器完成编译,对于浏览器推荐直接使用webpack编译。
一、安装 Jest
假定我们通过 vue-cli 创建了 webpack-simple 模板脚手架。接下来安装 Jest、vue-jest和Vue Test Utils。
npm install --save-dev jest babel-jest vue-jest @vue/test-utils
二、配置package.json
1、我们在package.json中定义一个单元测试的脚本。
// package.json { "scripts": { "test": "jest" } }
2、在package.json 中创建一个jest块:
"moduleFileExtensions": [ "js", "json", "vue" ], "moduleNameMapper": { "^@/(.*)$": "<rootDir>/src/$1" }, "transform": { "^.+\\.js$": "<rootDir>/node_modules/babel-jest", ".*\\.(vue)$": "vue-jest" }, "testURL": "http://localhost", "collectCoverage": true, "collectCoverageFrom": [ "src/components/*.{js,vue}", "!**/node_modules/**" ], "coverageReporters": [ "html", "text-summary" ]
三、配置babel
.babelrc 文件示例:
{ "presets": [["env", { "modules": false }]], "env": { "test": { "presets": [["env", { "targets": { "node": "current" } }]] } } }
为了仅在测试时应用这些选项,可以把它们放到一个独立的 env.test 配置项中 (这会被 babel-jest 自动获取)
四、编写测试
重点来了,编写测试代码如下:
import { mount } from '@vue/test-utils' import Counter from '@/components/Counter' describe('Counter.vue', () => { const wrapper = mount(Counter) it('should render the correct tag', () => { expect(wrapper.html()).toContain('<span class="count">1</span>') }) it('should have 2 buttons', () => { console.log(wrapper.findAll('button')) expect(wrapper.findAll('button')).toHaveLength(2) }) it('count default value should be one', () => { expect(wrapper.vm.count).toBe(1) }) it('should increment the count', () => { const button = wrapper.findAll('button').at(0) button.trigger('click') expect(wrapper.vm.count).toBe(2) }) it('should decrement the count', () => { const button = wrapper.findAll('button').at(1) button.trigger('click') expect(wrapper.vm.count).toBe(1) }) })
有没有注意到,现在已经不用引入Vue,因此也不依赖Vue组件的实例来创建测试用例。在Vue Test Utils中,通常会创建一个包含被挂载和渲染的 Vue 组件的包裹器。通过包裹器或包裹器数组的API来测试 Vue 组件。本实例中,我们用findAll替换了先前的querySelectorAll,用trigger方法替代了派发自定义事件。使用工具本身的API,是不是比原生的DOM API更优雅?
注意
本实例也设置了代码覆盖率,更多设置更多API用法请参考Vue Test Utils 官方文档
最新的vue cli3已经内置Vue Test Utils ,不需要手动配置,这样写vue测试就方便多了。感兴趣的话可以试一试。
😎Happy Test!