单元测试,顾名思义,就是为了测试代码的质量。对于某段代码或组件,如果通过单元测试后的代码覆盖率越高,说明该代码或组件鲁棒性更高,在生产环境中出现bug的机率越低。

代码覆盖率(code coverage)有四个测量维度,

行覆盖率(line coverage):是否每一行都执行了?
函数覆盖率(function coverage):是否每个函数都调用了?
分支覆盖率(branch coverage):是否每个if代码块都执行了?
语句覆盖率(statement coverage):是否每个语句都执行了?

本文简要介绍如何搭建一个支持 ES6 语法的单元测试环境,本工程demo源码可参考这里

本工程使用的相关工具介绍如下:

测试管理工具:Karma
测试框架:Mocha
断言库:Chai
测试浏览器:Chrome
测试覆盖率统计工具:Karma-Coverage

karma 配置文件内容:

// Karma configuration
module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['mocha'],
    files: [
      'test/**/*.js'
    ],
    exclude: [],
    preprocessors: {
      'test/**/*.js': ['webpack']
    },
    reporters: ['spec', 'coverage'],

    coverageReporter: {
      dir: 'coverage/',
      reporters: [
          { type: 'html' },
          { type: 'text'},
          { type: 'text-summary' }
      ]
    },
    
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    concurrency: Infinity,
    webpack: {
      module: {
        loaders: [{
          test: /\.js$/,
          loader: 'babel',
          exclude: /node_modules/,
          query: {
            presets: ['es2015'],
            plugins: ['istanbul']
          }
        }]
      }
    },
    webpackMiddleware: {
      noInfo: true
    }
  })
}

开始测试一段js代码 src/index.js:

function sum(x, y) {
  if(x<0) {
    return 0
  }
  return x+y
}

module.exports = {
  sum
}

写单元测试代码 test/index.js:

const chai = require('../node_modules/chai/chai');
const expect = chai.expect;
const Util = require('../src/index')
describe("test module src/index.js", function () {
  it("should return a number type", function () {
    let sum = Util.sum(30, 5);
    expect(sum).to.be.a('number');
    sum = Util.sum(-30, 5);
    expect(sum).to.be.a('number');
  });
});

工程结构如下图:
图片描述

package.json 内容:

{
  "name": "karma-example",
  "version": "1.0.0",
  "description": "karma example...",
  "main": "src/index.js",
  "directories": {
    "test": "test"
  },
  "scripts": {
    "test": "karma start"
  },
  "keywords": [
    "karma"
  ],
  "author": "hy",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.14.0",
    "babel-loader": "^6.2.5",
    "babel-plugin-istanbul": "^2.0.1",
    "babel-preset-es2015": "^6.14.0",
    "chai": "^4.1.0",
    "karma": "^1.3.0",
    "karma-chrome-launcher": "^2.2.0",
    "karma-coverage": "^1.1.1",
    "karma-mocha": "^1.3.0",
    "karma-spec-reporter": "^0.0.31",
    "karma-webpack": "^1.8.0",
    "mocha": "^3.4.2",
    "webpack": "^1.13.2"
  }
}

执行命令:
cnpm install
cnpm test

会自动打开chrome浏览器:
图片描述

测试代码执行完毕后,在控制台可见测试报告:
图片描述
也可打开 当前目录coverageChrome 59.0.3071 (Windows 7 0.0.0)index.html 查看网页版单元测试报告.
图片描述

如何调试单元测试代码?
点击DEBUG按钮,会打开一个新页签,F12打开控制台,即可调试。
图片描述


追寻
317 声望20 粉丝

混迹杭州 朝全栈的方向努力着...