養成良好的編碼習慣,一個合格的程序員須要掌握一些編寫單元測試的能力。單元測試也能夠總體上提高咱們的代碼質量,這裏介紹下 VUE 組件的單元測試。html
若是想直接經過 Demo 學習,能夠跳過下面的內容, 點擊這裏下載示例
karma.conf.js
文件用於 karma
的配置,使用 node_modules/.bin/karma init
命令建立該文件,咱們定義以下配置:vue
// Karma configuration const webpackConfig = require('./config/webpack.test.config.js') 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' ], // list of files / patterns to load in the browser files: [ 'test/**/*.spec.js' ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { 'test/**/*.spec.js': [ 'webpack', 'sourcemap' ] }, // webpack config webpack: webpackConfig, webpackMiddleware: { stats: 'errors-only' }, // 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: [ 'Chrome' ], // 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 }) }
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/node
import { expect } from 'chai' import { shallowMount } from '@vue/test-utils' import Header from '../src/components/Header' describe('Header', () => { const wrapper = shallowMount(Header) const header = wrapper.find('header') const h1 = 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
組件測試用例webpack
shallowMount
獲取 wrapper
chai
斷言庫編寫相關的測試用例i 「wdm」: Compiled successfully. 15 01 2020 18:28:13.799:INFO [karma-server]: Karma v4.4.1 server started at http://0.0.0.0:9876/ 15 01 2020 18:28:13.813:INFO [launcher]: Launching browsers Chrome with concurrency unlimited 15 01 2020 18:28:13.820:INFO [launcher]: Starting browser Chrome 15 01 2020 18:28:17.075:INFO [Chrome 79.0.3945 (Windows 10.0.0)]: Connected on socket PUKPz4iBuFzeVNSsAAAA with id 91716917 TOTAL: 4 SUCCESS
能夠看到咱們的單元測試已經經過了git
測試完成後,咱們須要查看測試覆蓋率報告。這須要在 webpack.test.config.js
和 karma.conf.js
中作一些配置修改程序員
const merge = require('webpack-merge') const path = require('path') const webpackCommonConfig = require('./webpack.common.config') const testConfig = { 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
模式module.exports = function(config) { config.set({ // ... coverageIstanbulReporter: { reports: [ 'html', 'text' ], fixWebpackSourcePaths: true }, reporters: [ 'coverage-istanbul' ] //... }) }
reporters
爲 [ 'coverage-istanbul' ]
,即便用 coverage-istanbul
reporterscoverageIstanbulReporter
配置項用於設置 coverage-istanbul
的參數,詳細的參數能夠參考 這裏 再次執行單元測試,咱們會看到測試覆蓋率的相關信息github
----------------|----------|----------|----------|----------|-------------------| File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s | ----------------|----------|----------|----------|----------|-------------------| All files | 100 | 100 | 100 | 100 | | Header.spec.js | 100 | 100 | 100 | 100 | | ----------------|----------|----------|----------|----------|-------------------|
也能夠經過生成到 coverage
目錄下的網頁文件,在瀏覽器中查看web