前言
最近发现一个问题,vue-cli 提供的官方模板确实好用。但一直用下来手贱毛病又犯了,像穿了别人的内衣,总感觉不舒服。
所以有机会就瞎倒腾了一遍,总算把各个流程摸了一把。这里分享一下配置带覆盖率的单元测试。分享出来供大家参考学习,话不多少了,来一起看看详细的介绍:
一、文件结构
基本的文件结构。
├─src│ ├─assets│ ├─components│ ├─app.vue│ └─main.js├─test│ └─unit│ ├─coverage│ ├─specs│ ├─index.js│ └─karma.conf.js├─.babelirc├─webpack.conf.js└─package.json
二、依赖
根据需要增删
yarn add -D /cross-env /# webpackwebpack /webpack-merge /vue-loader /# babelbabel-core /babel-loader /babel-plugin-transform-runtime /babel-preset-es2015 /babel-register /babel-plugin-istanbul /# karmakarma /karma-coverage /karma-phantomjs-launcher /karma-sourcemap-loader /karma-spec-reporter /karma-webpack /mocha /karma-mocha /sinon-chai /karma-sinon-chai /chai /sinon /
三、入口
先从 package.json 开始。跟官方的一致。设置 BABEL_ENV 可以在测试的时候才让 Babel 引入 istanbul 计算覆盖率。
{ "scripts": { "unit": "cross-env BABEL_ENV=test karma start test/unit/karma.conf.js --single-run", "test": "npm run unit", }}
四、配置 Babel
在 .babelirc 中:
{ "presets": ["es2015"], "plugins": ["transform-runtime"], "comments": false, "env": { "test": { "plugins": [ "istanbul" ] } }}
按需设置,写 Chrome Extension 的话用 es2016 就行。
Babel 的 istanbul 插件是个很聪明的做法。
五、Loader 配置
从 Vue Loader 的文档可以看到,不需要额外配置,它非常贴心自动识别 Babel Loader。
如果还测试 js 文件那么给源文件夹下的 js 文件配置 Babel Loader 就行。
以 src 为例:
{ module: { rules: [ { test: //.vue$/, loader: 'vue-loader' }, { test: //.js$/, loader: 'babel-loader', include: [ path.resolve(__dirname, '../src') ], exclude: /node_modules/ } ] }}
六、Karma 配置
为 webpack 设置环境
// karma.conf.jsconst merge = require('webpack-merge')let webpackConfig = merge(require('../../webpack.conf'), { devtool: '#inline-source-map', plugins: [ new webpack.DefinePlugin({ 'process.env': '"testing"' }) ]})// no need for app entry during testsdelete webpackConfig.entry
接着输出 karma 配置,基本沿用官方的配置。注意不同的浏览器需要安装不同的 karma 插件。
// karma.conf.jsmodule.exports = function (config) { config.set({ // to run in additional browsers: // 1. install corresponding karma launcher // http://karma-runner.github.io/0.13/config/browsers.html // 2. add it to the `browsers` array below. browsers: ['Chrome'], frameworks: ['mocha', 'sinon-chai'], reporters: ['spec', 'coverage'], files: ['./index.js'], preprocessors: { './index.js': ['webpack', 'sourcemap'] }, webpack: webpackConfig, webpackMiddleware: { noInfo: true }, coverageReporter: { dir: './coverage', reporters: [ { type: 'lcov', subdir: '.' }, { type: 'text-summary' } ] } })}
新闻热点
疑难解答
图片精选