培养良好的编码习惯,一个合格的程序员需要掌握一些编写单元测试的能力。单元测试还可以提高我们代码的整体质量。下面介绍一下VUE组件的单元测试。如果想直接通过Demo学习,可以跳过以下内容,点此下载示例技术栈@vue/test-utils[1.0.0-beta.30]istanbul-instrumenter-loader[3.0.1]karma[4.4.1]karma-chrome-launcher[3.1.0]karma-mocha[1.3.0]karma-sourcemap-loader[0.3.7]karma-coverage-istanbul-reporter[2.1.1]karma-webpack[4.0].2]webpack[4.41.5]定义karma配置的配置文件karma.conf.js文件,使用node_modules/.bin/karmainit命令创建该文件,我们定义如下配置://KarmaconfigurationconstwebpackConfig=require('./config/webpack.test.config.js')module.exports=function(config){config.set({//将用于解析所有模式(例如文件、排除)的基本路径basePath:'.',//要使用的框架//可用框架:https://npmjs.org/browse/keyword/karma-adapterframeworks:['mocha'],//要在浏览器中加载的文件/模式列表files:['test/**/*.spec.js'],//预处理匹配文件bef将它们提供给浏览器//可用的预处理器:https://npmjs.org/browse/keyword/karma-preprocessorpreprocessors:{'test/**/*.spec.js':['webpack','sourcemap']},//webpack配置webpack:webpackConfig,webpackMiddleware:{stats:'errors-only'},//web服务器端口端口:9876,//启用/禁用输出颜色(报告者和日志)颜色:true,//日志记录级别//可能的值:config.LOG_DISABLE||配置.LOG_ERROR||配置.LOG_WARN||配置.LOG_INFO||config.LOG_DEBUGlogLevel:config.LOG_INFO,//启用/禁用监视文件并在任何文件更改时执行测试autoWatch:true,//启动这些浏览器//可用的浏览器启动器:https://npmjs.org/browse/keyword/karma-launcherbrowsers:['Chrome'],//持续集成模式//如果为真,Karma捕获浏览器,运行测试并退出singleRun:false,//并发级别//应该启动多少个浏览器同时并发:无限})}设置框架为['mocha'],即使用mocha测试框架设置文件为['test/**/*.spec.js'],即设置预处理器为{'**/*.spec.js':['webpack','sourcemap']},即使用webpack,sourcemap将所有测试文件用webpack打包。设置浏览器为Chrome,即使用Chrome浏览器作为测试浏览器编写测试用例。关于@vue/test-utils的使用,详见https://vue-test-utils.vuejs.org/zh/import{expect}from'chai'import{shallowMount}from'@vue/test-utils'import来自'../src/components/Header'describe('Header',()=>{constwrapper=shallowMount(Header)constheader=wrapper.find('header')consth1=wrapper.find('h1')它('有标题标签',()=>{expect(header.exists()).to.be.true})it('有h1标签',()=>{expect(h1.exists()).to.be.true})it('h1的文字是“VUE单页模板”',()=>{expect(h1.text()).to.equal('VUE单页模板')})it('h1标签在header标签中',()=>{expect(header.contains('h1')).to.be.true})})这里我参考vue的Header组件测试用例-单页先通过shallowMount获取wrapper使用chai断言库编写相关测试用例运行结果i「wdm」:Comp成功启动。1501202018:28:13.799:INFO[karma-server]:Karmav4.4.1服务器启动于http://0.0.0.0:9876/1501202018:28:13.813:INFO[launcher]:以并发unlimited1501202018:28:13.820:INFO[launcher]:启动浏览器Chrome1501202018:28:17.075:INFO[Chrome79.0.3945(Windows10.0.0)]:ConnectedonsocketPUFzePzAA91716917TOTAL:4SUCCESS可以看到我们的单元测试通过了测试覆盖率报告测试完成后,我们需要查看测试覆盖率报告这需要在webpack.test.config.js和karma.conf.js中进行一些配置更改webpack.test.config.jsconstmerge=require('webpack-merge')constpath=require('path')constwebpackCommonConfig=require('./webpack.common.config')consttestConfig={devtool:'inline-source-map',mode:'none',module:{rules:[{test:/\.spec.js$/i,enforce:'pre',use:[{loader:'istanbul-instrumenter-loader',options:{esModules:true}}]}]}}module.exports=merge(webpackCommonConfig,testConfig)添加优先执行编译规则在.spec.js文件中,加载器使用istanbul-instrumenter-loader并打开esModules模式karma.conf.jsmodule.exports=function(config){config.set({//...coverageIstanbulReporter:{reports:['html','text'],fixWebpackSourcePaths:true},reporters:['coverage-istanbul']//...})}设置reporters为['coverage-istanbul'],即使用coverage-istanbulreporterscoverageIstanbulReporter配置项用于设置coverage-istanbul的参数。详细参数请参考这里的运行结果,再次进行单元测试。我们会看到测试覆盖率的相关信息------------------|----------|----------|-----------|------------|-----------------|文件|%Stmts|%分支|%函数|%行|未覆盖的行#s|--------------|------------|------------|-----------|------------|-------------------|所有文件|100|100|100|100||标头.spec.js|100|100|100|100||--------------|------------|--------|----------|-----------|--------------------|也可以在coverage中生成网页文件,在浏览器中查看参考资料目录https://vue-test-utils.vuejs.org/zh/https://github.com/mattlewis92/karma-coverage-istanbul-reporter
