以编程方式运行Mocha并将结果传递给变量或函数

dle*_*ous 20 javascript json mocha.js node.js

我使用ZombieJS和Chai在mocha中设置了一套测试.测试加载网站并检查是否正确地预订了各种服务并向网站的访问者显示.

我的目标是测试每天运行,然后将结果通过电子邮件发送给我的团队.测试都按预期运行,但我遇到的阻塞如下.

如何将JSON报告结果传递给另一个node.js脚本,我可以在其中通过电子邮件发送结果.构建电子邮件并发送它将使用nodemailer和下划线模板直接进行.

我目前的想法是有两种方法.使用shell脚本运行mocha测试,并将JSON输出传递给节点脚本,并从命令行参数处理JSON.就像是...

mocha test/services/homepage.js > node email.js
Run Code Online (Sandbox Code Playgroud)

另一种方法是从节点脚本中运行测试,并将返回的结果放入变量中.我一直在使用这里的信息在节点内运行测试.

https://github.com/mochajs/mocha/wiki/Using-mocha-programmatically

这运行正常,但我迷失了如何将JSON报告结果从下面的代码变为变量.

var Mocha = require('mocha'),
    Suite = Mocha.Suite,
    Runner = Mocha.Runner,
    Test = Mocha.Test;

// First, you need to instantiate a Mocha instance

var mocha = new Mocha({
    reporter: 'json'
});

var suite = new Suite('JSON suite', 'root');
var runner = new Runner(suite);
var mochaReporter = new mocha._reporter(runner);

mocha.addFile(
    '/Users/dominic/Git/testing-rig/test/services/homepage.js'
);

runner.run(function(failures) {
    // the json reporter gets a testResults JSON object on end
    var testResults = mochaReporter.testResults;

    console.log(testResults);
    // send your email here
});
Run Code Online (Sandbox Code Playgroud)

小智 44

您可以在https://github.com/mochajs/mocha/blob/master/lib/runner.js#L40中收听跑步者事件并构建您自己的报告.

var Mocha = require('mocha');

var mocha = new Mocha({});

mocha.addFile('/Users/dominic/Git/testing-rig/test/services/homepage.js')

mocha.run()
    .on('test', function(test) {
        console.log('Test started: '+test.title);
    })
    .on('test end', function(test) {
        console.log('Test done: '+test.title);
    })
    .on('pass', function(test) {
        console.log('Test passed');
        console.log(test);
    })
    .on('fail', function(test, err) {
        console.log('Test fail');
        console.log(test);
        console.log(err);
    })
    .on('end', function() {
        console.log('All done');
    });
Run Code Online (Sandbox Code Playgroud)