将测试 ID 添加到单元测试以进行报告

Adding test IDs to unit tests for reporting

我正在使用 mocha 并尝试构建一个单独报告测试的测试系统。目标是在项目需求和单元测试中定义的测试之间具有可追溯性。因此,例如,测试 'Must be able to create new widgets' 在需求数据库中,id 为“43”,我希望测试该条件的单元测试报告类似 Test 43, Must be able to create new widgets, pass 的内容,然后更新相应的数据库条目(另一项服务可能对此负责)。

这可以在 mocha 中完成吗?到目前为止我唯一发现的是用测试 id 替换 it() 函数中的文本,然后使用 json 报告器处理结果(但后来我没有得到文本对于正在测试的内容,除非我将它们组合起来并进行某种解析)。注意:并非所有测试都有 id。

这是我希望的那种功能的示例

describe("Widget" function() {
  it("should allow creation of widgets", function() {
    this.id = 43;
    result = widget.create();
    expect.result.to.exist;
  });
});

然后是钩子,比如

afterEach(function(test) {
  if (test.hasOwnProperty('id')) {
    report(test.result);
  }
});

或者自定义报告器,或者某种适配器。

runner.on('test end', function(test) {
  console.log(test.id); //doesn't exist, but i want it to
  report(test);
});

这取决于您的断言库。 使用 Chai,您有文本的可选字段。

assert.should.exist(result, 'expect Result to exist (Id 43)');

使用 Jasmine,您可以将测试引用添加到您的 it():

describe("Widget" function() {
  it("should allow creation of widgets (Id 43)", function() {

要使用 Mocha custom reporters,您可以尝试在您的测试套件中定义一个。

module.exports = MyReporter;

function MyReporter(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);
    process.exit(failures);
  });
}

这里确实有2条建议。第一种是最简单的,只需将您的 id 添加到 it() 的描述中,然后它就会显示通过和失败的内容。那将是达到目标的最快方法。

但是,如果您想要更高级的方法,并且可以进行测试以确保一切都已设置,那么您可以使用自定义报告器,如果未设置 ID,这将使您无法通过测试。

我想要的和存在的是如此接近!我能够使用记者中测试的 ctx 属性 来解决这个问题,例如test.ctx.id

test.js

describe("Widget" function() {
  it("should allow creation of widgets", function() {
    this.id = 43;
    result = widget.create();
    expect.result.to.exist;
  });
});

reporter.js

runner.on('test end', function(test) {
  console.log(test.ctx.id);
  report(test);
});