purpose
Build a basic test tool that consists of Karma + Mocha + Chai + Istanbul + ES6 + webpack
A brief introduction to the tool
The test framework
Mocha
Mocha is a unit testing framework for JavaScript that can be run in either a browser or node.js environment. With Mocha, we can just focus on writing the unit tests themselves, and then let Mocha automate all the tests and produce the results. The main features of Mocha are:
- You can test simple JavaScript functions as well as asynchronous code, since asynchrony is a feature of JavaScript;
- You can run all tests automatically, or you can run only specific tests;
- Initialization code can be written with support for before, after, beforeEach, and afterEach.
Test framework Mocah example tutorial by Liao Xuefeng JS tutorial
Chai assert library
Chai provides three assertion styles to apply to BDD and TDD respectively. The Expect/Should API corresponds to the BDD style, and the Assert API corresponds to the TDD style.
Chai official website API Reference Chai. Js Assertion library API Chinese documentation
Front-end testing tool
Karma
Karma is a JavaScript Test Runner based on Node.js. The tool can be used to test all major Web browsers, integrated into the Continuous Integration (CI) tool, or used with other code editors. A powerful feature of the test tool is that it can monitor changes to the Watch file and then perform them on its own, displaying test results through console.log.
Karma’s official website
Istanbul
When testing, we often care about whether all code is tested. This metric is called code Coverage. It has four dimensions of measurement.
- Line coverage: Is every line executed?
- Function coverage: Is every function called?
- Branch Coverage: Is every if block executed?
- Statement coverage: Is every statement executed?
Code coverage tool Istanbul Tutorial
practice
Overview of file structure
Karma_mocha —– project folder
|
| – node_modules — — — — — project dependencies
|
|—src
| — — — — — – the add. Js – file under test
|
|—test
| — — — — — – coverage – automatic production report folder
|——mochaDemo
| — — — — — — — — — add. Spec. Js file — — — — — test cases
| — — — — — – karma. Conf., js – karma configuration file
|
. | – babelrc — — — — — the Babel configuration file
| – package. Json – NPM configuration file
| – webpack. Config. Js – webpack configuration file
Initial Configuration
Karma configuration
const webpack = require('.. /webpack.config.js')
module.exports = function(config) {
config.set({
basePath: ' '.port:1010.// Automatically enable the Chrome browser execution code karma-chrome-launcher
browsers: ['Chrome'].// Tell Karma which test framework (Mocha) and assertion library (karma-chai) to use
frameworks: ['mocha'.'chai'].// Test report display format (command line display format) karma-mocha-reporter
// Test coverage report karma-coverage
reporters: ['spec'.'coverage'].//colors Whether the report is color-coded
colors:true.// Load the functional code and test code into karma
files: [
'mochaDemo/**/*.spec.js'].// Exclude files, which can be re
exclude: ["karma.conf.js"].// Preprocess the specified file
preprocessors: {
'mochaDemo/add.spec.js': ['webpack']},// webpack
webpack: webpack,
// Ignore packaging information while testing
webpackMiddleware: {
noInfo: true
},
// Generated coverage report configuration items
// coverageReporter: {
// type : 'html',
// dir : 'coverage/'
// }
coverageReporter: {
dir: './coverage'.reporters: [{type: 'lcov'.subdir: '. ' },
{ type: 'text-summary' } // Output a summary on the console]},// Detect file changes Automatically execute test files
autoWatch: true.// Log level of output
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// Whether to run with the browser
singleRun:false.// Concurrency, how many browsers are supported at the same time
concurrency:Infinity
});
};
Copy the code
Babel configuration
{
"presets": [["env", {
"modules": false."targets": {
"browsers": ["1%" >."last 2 versions"."not ie <= 8"]}}],"stage-2"]."plugins": ["transform-vue-jsx"."transform-runtime"]."env": {
"test": {
"presets": ["env"."stage-2"]."plugins": ["transform-vue-jsx"."istanbul"]}}}Copy the code
Webpack configuration
module.exports = {
module: {
rules: [{test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"}}]}};Copy the code
Package. json Modify script
"scripts": {
"test": "cross-env BABEL_ENV=test karma start test/karma.conf.js"
}
Copy the code
Install dependencies
"babel-core": "^ 6.26.3"."babel-loader": "^ 7.1.1." "."babel-plugin-syntax-jsx": "^ 6.18.0"."babel-plugin-transform-runtime": "^ 6.23.0"."babel-plugin-transform-vue-jsx": "^ 3.7.0"."babel-preset-env": "^ 1.7.0"."babel-preset-stage-2": "^ 6.24.1"."chai": "^ 4.2.0"."cross-env": "^ 5.2.0." "."karma": "^ 4.0.1." "."karma-chai": "^ 0.1.0 from"."karma-chrome-launcher": "^ 2.2.0." "."karma-coverage": "^ 1.1.2." "."karma-mocha": "^ 1.3.0"."karma-spec-reporter": "0.0.32"."karma-webpack": "^ 2.0.2"."mocha": "^ 6.0.2." "."webpack": "^ 3.6.0"
"babel-plugin-istanbul": "^ 4.4.1"
Copy the code
Functional test Demo
For the file
//add.js
function add(x, y) {
return x + y
}
module.exports = add;
Copy the code
The test case
//add.spec.js
var add = require('.. /.. /src/add.js');
var expect = require('chai').expect;
describe('Test of addition function'.function() {
it('One plus one is two'.function() {
expect(add(1.1)).to.be.equal(2);
});
});
Copy the code
Interface Test Demo
The interface test used the chai plug-in chai-http, see the chai-http official website. There are other HTTP testing tools, such as Supertest.
Karma. Conf. js Adds proxies to multiple requests.
module.exports = function(config) {
config.set({
...
/ / agent
proxies: {
'/': 'http://192.168.23.170:29548'}}); };Copy the code
Add HTTP request tests
. var chai = require('chai'); var chaiHttp = require('chai-http'); chai.use(chaiHttp); Describe (' interface test ', function() {... It (' Database list interface requested successfully ', Done => {chai. Request ("http://localhost:1010") // This port is the port configured in karma. Conf.js .post('/djtest/projectConfig/listDataBase.do') .set('Content-Type', 'application/json') .send({ 'fprojectId': '', 'fsort': '', 'pagenum': 1, 'pagesize': 10 }) .end((err, res) => { if (err) { done(); } let data = JSON.parse(res.text); expect(data.success).to.be.true; done(); }); }); });Copy the code
Run the NPM run test on the terminal
The console can see the output
Create the coverage folder in the test directory and open index.html
Use in VUE projects
Vue Test Utils is the official Vue. Js unit Test utility library. NPM install — save-dev@vue /test-utils
import ElementUI from "element-ui";
import vueComponent from "@/demo/vueComponent.vue"; // VUE component to be tested
import { createLocalVue, mount } from "vue-test-utils"; // the method provided by vue-test-utils
const localVue = createLocalVue();
// Return a Vue class where you can add components, mix in, and install plug-ins without contaminating the global Vue class
localVue.use(ElementUI); // Register element UI
const wrapper = mount(dataBaseManagement, {
localVue
}); // Create a Wrapper containing the Vue components to be mounted and rendered
// Start writing test cases
Copy the code
Reference article:
All that front-end testing stuff