简体   繁体   English

如何在Node.js中处理Mocha测试的结果?

[英]How to manipulate results of Mocha test in Node.js?

I have a simple Mocha file: 我有一个简单的摩卡文件:

const assert = require('assert');

describe('Array', function () {
  describe('#indexOf()', function () {
    it('should return -1 when the value is not present', function () {
      assert.equal([1, 2, 3].indexOf(4), -1);
    });
  });
});

I'm looking to run the test above inside Node.js and get access to the test results for further manipulation. 我希望在Node.js中运行上面的测试,并访问测试结果以进行进一步的操作。

I know it's possible to import Mocha and run tests, like this: 我知道可以导入Mocha并运行测试,如下所示:

const Mocha = require('mocha');

const test = new Mocha();
test.addFile('./assert.js');
test.run();

But, I'd like a way of getting the result of assert.equal and the corresponding descriptions, perhaps via the then() method. 但是,我想要一种可能通过then()方法获取assert.equal和相应描述的结果的方法。 Any ideas? 有任何想法吗? Could Sinon.JS help? Sinon.JS可以Sinon.JS帮助吗?

The end goal is to display these tests in the browser, using an API endpoint. 最终目标是使用API​​端点在浏览器中显示这些测试。

You can use the instance of test and look for events for each test execution. 您可以使用test实例,并为每次测试执行查找事件。

for example: 例如:

const Mocha = require('mocha');

const test = new Mocha();
test.addFile('./assert.js');
let runner = test.run();

runner.on('pass', (e) => {
    passed.push({
        title: e.title,
        speed: e.speed,
        duration: e.duration,
        file: e.file
    });
});

runner.on('fail', (e) => {
    failed.push({
        title: e.title,
        err: error,
        file: e.file
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM