使用Karma做vue组件单元测试的实现
养成良好的编码习惯,一个合格的程序员需要掌握一些编写单元测试的能力。单元测试也可以整体上提升我们的代码质量,这里介绍下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.conf.js文件用于karma的配置,使用node_modules/.bin/karmainit命令创建该文件,我们定义如下配置:
//Karmaconfiguration
constwebpackConfig=require('./config/webpack.test.config.js')
module.exports=function(config){
config.set({
//basepaththatwillbeusedtoresolveallpatterns(eg.files,exclude)
basePath:'.',
//frameworkstouse
//availableframeworks:https://npmjs.org/browse/keyword/karma-adapter
frameworks:['mocha'],
//listoffiles/patternstoloadinthebrowser
files:[
'test/**/*.spec.js'
],
//preprocessmatchingfilesbeforeservingthemtothebrowser
//availablepreprocessors:https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors:{
'test/**/*.spec.js':['webpack','sourcemap']
},
//webpackconfig
webpack:webpackConfig,
webpackMiddleware:{
stats:'errors-only'
},
//webserverport
port:9876,
//enable/disablecolorsintheoutput(reportersandlogs)
colors:true,
//leveloflogging
//possiblevalues:config.LOG_DISABLE||config.LOG_ERROR||config.LOG_WARN||config.LOG_INFO||config.LOG_DEBUG
logLevel:config.LOG_INFO,
//enable/disablewatchingfileandexecutingtestswheneveranyfilechanges
autoWatch:true,
//startthesebrowsers
//availablebrowserlaunchers:https://npmjs.org/browse/keyword/karma-launcher
browsers:['Chrome'],
//ContinuousIntegrationmode
//iftrue,Karmacapturesbrowsers,runsthetestsandexits
singleRun:false,
//Concurrencylevel
//howmanybrowsershouldbestartedsimultaneous
concurrency:Infinity
})
}
- 设置frameworks为['mocha'],即使用mocha测试框架
- 设置files为['test/**/*.spec.js'],即对test目录下所有的后缀为.spec.js文件测试
- 设置preprocessors为{'**/*.spec.js':['webpack','sourcemap']},即使用webpack,sourcemap对所有的测试文件进行webpack打包
- 设置browsers为Chrome,即使用Chrome浏览器作为测试浏览器
编写测试用例
详细的关于@vue/test-utils用法,查看https://vue-test-utils.vuejs.org/zh/
import{expect}from'chai'
import{shallowMount}from'@vue/test-utils'
importHeaderfrom'../src/components/Header'
describe('Header',()=>{
constwrapper=shallowMount(Header)
constheader=wrapper.find('header')
consth1=wrapper.find('h1')
it('有header标签',()=>{
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-single-page的Header组件测试用例
- 首先通过shallowMount获取wrapper
- 使用chai断言库编写相关的测试用例
运行结果
i「wdm」:Compiledsuccessfully.
1501202018:28:13.799:INFO[karma-server]:Karmav4.4.1serverstartedathttp://0.0.0.0:9876/
1501202018:28:13.813:INFO[launcher]:LaunchingbrowsersChromewithconcurrencyunlimited
1501202018:28:13.820:INFO[launcher]:StartingbrowserChrome
1501202018:28:17.075:INFO[Chrome79.0.3945(Windows10.0.0)]:ConnectedonsocketPUKPz4iBuFzeVNSsAAAAwithid91716917
TOTAL:4SUCCESS
可以看到我们的单元测试已经通过了
测试覆盖率报告
测试完成后,我们需要查看测试覆盖率报告。这需要在webpack.test.config.js和karma.conf.js中做一些配置修改
webpack.test.config.js
constmerge=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文件的rules,loader使用istanbul-instrumenter-loader并开启esModules模式
karma.conf.js
module.exports=function(config){
config.set({
//...
coverageIstanbulReporter:{
reports:['html','text'],
fixWebpackSourcePaths:true
},
reporters:['coverage-istanbul']
//...
})
}
- 设置reporters为['coverage-istanbul'],即使用coverage-istanbulreporters
- coverageIstanbulReporter配置项用于设置coverage-istanbul的参数,详细的参数可以参考这里
运行结果
再次执行单元测试,我们会看到测试覆盖率的相关信息
----------------|----------|----------|----------|----------|-------------------| File|%Stmts|%Branch|%Funcs|%Lines|UncoveredLine#s| ----------------|----------|----------|----------|----------|-------------------| Allfiles|100|100|100|100|| Header.spec.js|100|100|100|100|| ----------------|----------|----------|----------|----------|-------------------|
也可以通过生成到coverage目录下的网页文件,在浏览器中查看
参考资料
https://vue-test-utils.vuejs.org/zh/
https://github.com/mattlewis92/karma-coverage-istanbul-reporter
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。
