Vue project code coverage report generation

Goal: To display the percentage of code executed by its individual code files in the code coverage report by clicking on the generation of the code coverage report at native code runtime

Start by using vue-CLI to create a new project called Istanbul

vue create istanbul
Copy the code

Enter the project and download the package

cd istanbul
yarn
Copy the code

Download the plugin

yarn add --dev babel-plugin-istanbul chalk concurrently live-server nodemon rimraf axios express nyc
Copy the code

The Local service Nodemon, concurrently run multiple commands with live Server to automatically refresh browser tabs Nodejs local service Rimraf listens for files and automatically flushes files and folders AXIos Network Request Express Local Service NYC code coverage report generation tool

Modify the Babel. Config. Js

module.exports = {
  presets: ['@vue/cli-plugin-babel/preset'].plugins: [['istanbul',
      {
        "useInlineSourceMaps": false.extension: ['.js'.'.vue'[}]]};Copy the code

Modify the package.json file

  "scripts": {
    "test": "concurrently \"npm run nodemon\" \"npm run serve\""."nodemon": "nodemon autoIstanbul.js --watch"."serve": "vue-cli-service serve"."build": "vue-cli-service build"."lint": "vue-cli-service lint"
  },
  "nyc": {
    "reporter": [
      "html"."text-summary"]."extension": [
      ".js".".vue"]},Copy the code

Add the file nycclient.js to the SRC/directory for the front-end project to trigger code coverage reports

import axios from 'axios';

let istanbulSync = () = > {
  axios.post(
    'http://127.0.0.1:11118/istanbulSync',
    {
      coverage: JSON.stringify(window.__coverage__)
    },
    (res) = > {
      console.log('res', res); }); };window.onload = () = > {
  istanbulSync();
};
document.body.addEventListener('click', istanbulSync);

Copy the code

Introduce the nycclient.js file in main.js

import './nycClient.js';
Copy the code

The most critical step is automatic coverage reporting of local service files

Create autoIstanbul. Js and place it in the root directory

const fs = require('fs');
const express = require('express');
const app = express();
const { execSync } = require('child_process');
const liveServer = require('live-server');
const chalk = require('chalk');
const rimraf = require('rimraf');

// Clear the folder
rimraf.sync('./.nyc_output/');
fs.mkdirSync('./.nyc_output');

// Set cross-domain
app.all(The '*'.function(req, res, next) {
  res.header('Access-Control-Allow-Origin', req.headers.origin);
  res.header('Access-Control-Allow-Headers'.'Content-Type');
  res.header('Access-Control-Allow-Credentials'.'true');
  res.header('Access-Control-Allow-Methods'.The '*');
  res.header('Content-Type'.'application/json; charset=utf-8');
  next();
});
// Set the size to receive JSON
app.use(express.json({
  limit: '100mb'
}));
app.use(express.urlencoded({ extended: true }));

// Set the static page self-test
app.get(The '*'.(req, res) = > {
  res.send('autoIstanbul.js');
});

// Receive front-end parameters
app.post('/istanbulSync'.async (req, res) => {
  let parse = JSON.parse(req.body.coverage);
  let date = new Date().getTime();
  fs.writeFileSync(`./.nyc_output/${date}.json`.JSON.stringify(parse));
  let message = 'Code coverage synchronization successful! ';
  try {
    execSync('nyc report --reporter=html', { encoding: 'utf8' });
  } catch (error) {
    message = 'Code coverage synchronization failed! ' + error;
  }
  console.log(chalk.green(message));
  res.send(`${message}, live preview address: http://localhost:11119 ');
});
// Start the code coverage back-end service
app.listen(11118.() = > {
  console.log(chalk.cyan('listening sync: http://localhost:11118'));
});

// Start the code coverage front TAB automatic refresh service
let params = {
  port: 11119.host: '0.0.0.0'.root: './coverage'.open: false.file: 'index.html'.logLevel: 0.middleware: [
    function(req, res, next) { next(); }}; liveServer.start(params);console.log(chalk.cyan('listening showHtml: http://localhost:11119'));
Copy the code

Run the project

yarn test
Copy the code

View the VUE project

http://localhost:8080
Copy the code

View the code coverage report

http://localhost:11119
Copy the code