[英]How do I access mocha's json report from a script?
Mocha can be invoked from a script and it has a useful JSON reporter , but how can one access that reported structure from the invoking script? Mocha 可以从脚本调用,它有一个有用的JSON 报告器,但是如何从调用脚本访问报告的结构呢? Redirecting stdout worked:
重定向标准输出有效:
var Mocha = require('mocha');
var stats = {};
var oldWrite = process.stdout.write;
process.stdout.write = function(txt) {
stats = JSON.parse(txt).stats; // write invoked in one gulp.
};
new Mocha().
addFile("test/toyTest").
reporter("json", {stats: stats}).
run(function (failures) {
process.on('exit', function () {
process.stdout.write = oldWrite;
console.log("percentage: " + stats.passes/(stats.passes+stats.failures));
process.exit(failures > 0 ? 1 : 0);
});
});
but I'd have expected a more direct solution.但我期待更直接的解决方案。
According to the code , the answer was "you can't":根据代码,答案是“你不能”:
process.stdout.write(JSON.stringify(obj, null, 2));
Since the my solution above is somewhat less than obvious, I created a pull request to add a reporter option to pass in a target object:由于我上面的解决方案不太明显,我创建了一个拉取请求来添加一个报告器选项来传递一个目标对象:
var Mocha = require('mocha');
var report = {};
new Mocha().
addFile("test/toyTest").
reporter("json", {"output-object": report}).
run(function (failures) {
process.on('exit', function () {
var s = report.stats;
console.log("percentage: " + s.passes/(s.passes+s.failures));
process.exit(failures > 0 ? 1 : 0);
});
});
which saves capturing process.stdout.write as well as the needless serialization and deserialization of the report structure.这节省了捕获 process.stdout.write 以及报告结构的不必要的序列化和反序列化。 I also added a command line to set the output file so you can run:
我还添加了一个命令行来设置输出文件,以便您可以运行:
mocha -R json --reporter-options output-file=rpt.json
An alternative solution is to create your own reporter like it has been suggested in the documentation .另一种解决方案是创建您自己的报告程序,就像文档中所建议的那样。 I simply copied the json reporter in
node_modules/mocha/lib/reporters/json.js
to new file in my project folder companyReporter.js
and replaced this line我只是将
node_modules/mocha/lib/reporters/json.js
的 json 报告器复制到我的项目文件夹companyReporter.js
新文件并替换了这一行
Ln 69: process.stdout.write(JSON.stringify(obj, null, 2));
With和
Ln 69: process.send(obj);
It was also necessary to update the paths to the requires on line 9 and 10 of myReporter.js
.还需要更新
myReporter.js
第 9 和 10 行的 requires 路径。 I prefer this way because I'm not messing with process.stdout.write
.我更喜欢这种方式,因为我不会弄乱
process.stdout.write
。
The last change to the code was updating the reporter path:对代码的最后更改是更新报告路径:
var Mocha = require('mocha');
process.on('message', function (message) {
const test = message.toString('utf8').replace(/\n$/,'');
new Mocha().
addFile(test).
reporter(__dirname + '/path/to/myReporter.js').
run(function(failures) {
process.exit(failures > 0 ? 1 : 0);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.