Here I document setting up a test environment based on Karma + Mocha + Webpack3 + VUE2. I found a deep pit after a period of time, so make a note in case I fall into the pit again. It would be even better if this article could solve your problems, right?

1. Which packages need to be installed

Just install them in your project as the packages listed below, and a few more packages need to be installed globally: Babel, Mocha, and Karma

6. Relating to Babel:

  • babel-core
  • Babel-plugin-syntax-jsx // Supports JSX syntax
  • Babel – plugin – transform – runtime / / describe too obscure, the official document: https://github.com/babel/babe…
  • Babel-plugin-transform-vue-jsx // Supports vue2. X JSX syntax
  • Babel-preset-env // Automatically determines which Babel plug-ins and polyfills you need based on the environment you support (.babelrc configuration)
  • babel-preset-es2015
  • babel-preset-stage-2
  • babel-runtime
  • Babel – Polyfill // Supports older browsers

Karma, Mocha, Assertion packages

  • karma
  • mocha
  • Chai // BDD, TDD Assertion Framework
  • Chalk // The terminal can add color to the output content
  • karma-mocha
  • Karma-coverage // Generate code coverage
  • Karma-phantomjs-launcher // PhantomJS launcher
  • Karma-phantomjs-shim // You can support features that PhantomJS does not support by default, such asObject.assign, etc…
  • karma-sinon-chai
  • Karma-spec-reporter // Output test results from the terminal
  • Karma -webpack // karma supports webpack pluginsCan't find the requirejs“Error message
  • PhantomJS -prebuilt // phantomJS installed via NPM
  • SINON // test auxiliary tools, provide spy, stub, mock three test means, simulate a specific scene
  • sinon-chai

Webpack related

  • webpack
  • babel-loader
  • css-loader
  • Istanbul-instrument-loader // Code coverage statistics tool
  • karma-sourcemap-loader
  • style-loader
  • url-loader
  • vue-loader
  • vue-style-loader
  • extract-text-webpack-plugin

Vue core packages

  • vue
  • vue-template-compiler
  • vue-router

2. How to configure

Now that the big package is installed, it’s time to configure it. There are two main configurations. One is the configuration file for Karma, and the other is the Webpack configuration file for Karma. Webpack configuration files are used to parse the source files that need to be tested, namely VUE related files, and then identify them for Karma’s unit test cases.

Webpack3 configuration file I manually created a webpack.test.config.js file and then the content was configured as follows

For more information on Webpack, refer to an article I wrote earlier

var path = require("path") var webpack = require("webpack") var ExtractTextPlugin = require('extract-text-webpack-plugin') function resolve(dir) { return path.join(__dirname, '.. ', dir) } var webpackConfig = { module: { rules: [ // babel-loader { test: /\.js$/, use: 'babel-loader', include: [resolve(' SRC '), resolve('test')]}, // ISTanbul-instrumenter-loader {test: /\.(js)$/, exclude: /node_modules/, include: /src|packages/, enforce: 'post', use: [{ loader: "istanbul-instrumenter-loader", options: { esModules: true }, }] }, // vue loader { test: /\.vue$/, use: [{ loader: 'vue-loader', options: ListenIstanbul-Instrumenter-Loader Preloaders: {js: 'istanbul-instrumenter-loader?esModules=true' } } }] }, // css loader { test: /\.css$/, use: ExtractTextPlugin.extract({ use: 'css-loader', fallback: 'vue-style-loader' }) }, // img loader { test: /\.(png|gif|jpe?g)(\?\S*)?$/, use: [{loader: 'url-loader'}] }, // font loader { test: /\.(eot|woff|woff2|ttf|svg)(\?\S*)?$/, use: [{loader: 'url-loader'}] }, ] }, resolve: { extensions: ['. Js', 'vue', 'json'], alias: {' vue $' : 'vue/dist/vue. Esm. Js',' @ ': resolve (' SRC'), / / when the calling component convenient point}}, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }) ] } module.exports = webpackConfig

The karma configuration file

CD directly to your project and execute the following command, which will prompt you to use require.js, browser environment, test script location, etc.

$ karma init

This will then generate a karmat.config.js file, which I’m using as a direct copy of the official Vue-CLI example:

var webpackConfig = require('.. /.. /build/webpack.test.config'); module.exports = function (config) { config.set({ // to run in additional browsers: / / 1. Install corresponding karma the launcher / / http://karma-runner.github.io/0.13/config/browsers.html / / 2. Add it to the `browsers` array below. browsers: ['PhantomJS'], frameworks: ['mocha', 'sinon-chai', 'phantomjs-shim'], reporters: ['spec', 'coverage'], files: ['index.js'], preprocessors: { './index.js': ['webpack', 'sourceMap ']}, WebpackMiddleware: {noInfo: true}, WebpackServer: {noInfo: true}, true }, webpack: webpackConfig, coverageReporter: { dir: './coverage', reporters: [ { type: 'lcov', subdir: '.' }, { type: 'text-summary' } ] } }) }

3. Build directory structure

├─ Build │ webpack.test.config. JS │ ├─ SRC │ ├─package.json │ ├─ test ├─ Unit │ index.js │ karma └ ─ specs *. Spec. Js

Instrument.js (” instrument.js “, “instrument.js”, “instrument.js”, “instrument.js”, “instrument.js”, “instrument.js”, “instrument.js”, “instrument.js”) Test the main entry file index.js with the following contents:

Import Vue from 'Vue' vue.config.productionTip = false // require all test files (files that ends with .spec.js) const testsContext = require.context('./specs', true, /\.spec$/) TestsContext.keys ().foreach (TestsContext) // require all SRC files except Main.js to be overwritten // require all SRC files except Main.js to be overwritten  for coverage. // you can also change this to match only the subset of files that // you want coverage for. const srcContext = require.context('.. /.. /src', true, /^\.\/(? ! main(\.js)? $)/) srcContext.keys().forEach(srcContext)

Simple unit testing of VUE components

We create a hello.vue component in the SRC directory


<template>
   <div>msg</div>
</template>
<script>
export default {
  name: 'hello',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>

Then create a hello.spec.js file under test/unit/specs and write a simple unit test case:

import Vue from 'vue'
import Hello from '@/components/Hello'

describe('Hello.vue', () => {
  it('should render correct contents', () => {
    const Constructor = Vue.extend(Hello)
    const vm = new Constructor().$mount()
    expect(vm.$el.querySelector('.hello h1').textContent)
      .to.equal('Welcome to Your Vue.js App')
  })
})

5. Test output

Configure the command in package.json:

 // package.json
 "scripts": {
    "test": "karma start test/unit/karma.config.js --single-run"
  }

Output results:

Also generate test reports in Test/Unit/Coverage. The above is a simple VUE unit test example. Finally, the source code

It started on my personal blog