3

为 Mocha.js 编写自定义的 reporter

 3 years ago
source link: https://www.lfhacks.com/tech/mocha-reporter
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

为 Mocha.js 编写自定义的 reporter

982.jpg

Mocha.js 有一些自带的 reporter,但是这些有时候不能完全满足自己的需求,有些信息冗余,有些信息缺失。其实我们可以自己编写reporter。

自定义reporter

如果你对 Mocha 文档里介绍的一些 自带的reporter 不满意,还可以发挥创造力,自己编写 reporter 的函数。使用下面的方式调用

mocha --reporter reporter.js

或者用 mocharc 配置文件:

"reporter": "reporter.js"

这篇官方 wiki 介绍了一个基本可用的例子:

var mocha = require('mocha');
module.exports = MyReporter;

function MyReporter(runner) {
  mocha.reporters.Base.call(this, runner);
  var passes = 0;
  var failures = 0;

  runner.on('pass', function(test) {
    passes++;
    console.log('pass: %s', test.fullTitle());
  });

  runner.on('fail', function(test, err) {
    failures++;
    console.log('fail: %s -- error: %s', test.fullTitle(), err.message);
  });

  runner.on('end', function() {
    console.log('end: %d/%d', passes, passes + failures);
  });
}

如此看来,自定义reporter的编写其实很简单:只要自定义一个函数,在函数的参数 runner 上注册已有的事件钩子即可。

支持的事件钩子有如下几种:

事件名称 触发条件 回调函数的参数 属性 “start” 整个测试开始执行时 无 “end” 整个测试执行结束时 无 “suite” 测试集(describe 所定义的用例集合)开始执行时触发 suite suite.title suite的名称,也就是describe 里规定的描述 “suite end” 测试集(以及所有的子集)执行结束 suite “test” 单个测试用例(it 所定义的用例集合)执行开始 test test.title test的名称,也就是 it 里规定的描述文字 test.fullTitle() 包含所属 suite 的 test的名称 “test end” 单个测试用例执行结束 无 “pass” 单个测试用例执行通过 test “fail” 单个测试用例执行失败 test, err “pending” 单个测试用例执行暂不执行 test

注意,除了describe 定义的suite以外,还有一个默认的“顶级”suite,包含所有要执行的 describe 的顶级集合。虽然在用例执行过程中不可见,但是会触发 “suite” 和 “suite end” 事件。“顶级”suite有一个字段 root=true ,可以用于排除,例如:

runner.on("suite", function(suite) {
    if (suite.root) {
      return;
    }
    ....
}

runner的属性

函数的参数 runner,是测试的执行器,包含了测试过程相关的信息:比如 runner.stats 包含了统计信息

stats: { 
    suites: 0, 
    tests: 0, 
    passes: 0, 
    pending: 0, 
    failures: 0
} 

继承 reporter

官方例子 的最后,还有一句如何继承已有 reporter 的方法:

// To have this reporter "extend" a built-in reporter uncomment the following line:
// mocha.utils.inherits(MyReporter, mocha.reporters.Spec);

比如我想继承默认的失败原因列表,如下图:

这个列表来自 reporter 基类的 epilogue() 函数,如果自己写会很麻烦,但是只需要一行语句就可以继承下来:

runner.once("end", this.epilogue.bind(this));

mocha.utils.inherits(MyReporter, mocha.reporters.Base);

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK