目录
1、相关工具介绍
- chai.js 断言库 :这个玩意儿就是对你写的代码进行一个单元测试,能够使开发人员尽早的发现代码中的 bug。
- Karma(
[ˈkɑrmə]卡玛):一个测试运行器的工具,它可以呼起浏览器,加载测试脚本,然后运行测试用例。 - Mocha(
[ˈmoʊkə]摩卡):这也是一个单元测试框架/库,它可以用来写测试用例,监测代码中可能存在的问题。 - Sinon(西农):一个 spy / stub / mock 库,用以辅助测试,比如测试 click 函数是否能被正常调用等。
个人认为测试在软件开发的过程中还是很重要的一个环节的,一般开发人员在测试的过程中会使用到以上几个库或工具,其详细的使用方法可以到各自的官网或 github 上查看,这里就不赘述了,主要说一下在 Vue 项目中如何使用 Karma 做自动化测试,进而提高测试效率。
在 Vue 项目中的测试用例一般写在根目录的 test 文件夹内,在写测试用例之前你需要安装和引入相关的单元测试框架和库:
npm install -D chai chai-spies // chai.js 库
npm install -D karma karma-chrome-launcher karma-mocha karma-sinon-chai
mocha sinon sinon-chai karma-chai karma-chai-spies //其他相关工具
这里假定你已经写好测试用例了,每次运行测试用例都需要手动打开浏览器,查看控制相关的报错信息,这个过程比较费时间,最好能配置一下让整个过程自动化进行。
2、Karma 的具体配置
在项目根目录下新建 karma.conf.js 文件,内容其实不需要深究,这里简单说两个配置选项,`files` 是测试用例打包后的文件所在位置,`browers` 代表默认打开的浏览器。具体的配置内容如下:
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'sinon-chai'],
client: {
chai: {
includeStack: true
}
},
// list of files / patterns to load in the browser
files: [
'dist/**/*.test.js',
'dist/**/*.test.css'
],
// list of files / patterns to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['ChromeHeadless'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
3、执行自动化测试脚本
创建测试脚本,在 package.json 里面编写执行脚本:
"scripts": {
"dev-test": "parcel watch test/* --no-cache & karma start", //watch
"test": "parcel build test/* --no-minify && karma start --single-run" //一次性运行
}
- 使用 `
npm run test` 一次性运行(--single-run)。如果存在不知道的错误,可以尝试删除缓存重新打包。 - 或使用 `
npm run dev-test` 进行 watch 运行,修改代码后会自动进行重新打包测试。
运行命令后,会执行 package.json 里面编写执行脚本,先打包 test 目录下的测试用例,然后打开浏览器进行测试,运行完毕后将测试结果可以直接显示到命令行上,十分的方便。
如果实在是懒到连 npm 脚本都不想写 ,还可以通过持续集成的方式进行代码测试,推荐:阮一峰:持续集成服务 Travis CI