如何以编程方式在 Mocha 测试中获得详细结果?

How to get verbose results in Mocha tests programmatically?

是否可以以编程方式 运行 Mocha,但 运行 它处于 "verbose" 模式并以编程方式使用结果?

现在我通过 mocha 模块在 NodeJS 中使用它(在套件内部使用 chai 进行断言)。 我想要的是获得更多关于失败测试的数据,而不是样式的一般错误:"expected true and got false".

例如,在测试中有多个断言的情况下,是否有一种方法可以检查哪个断言失败以及原因,或者接收有关特定测试的更多信息,如果是,如何?

当你run Mocha programmatically时,mocha.run()方法returns一个Runner对象。如果您收听 fail 事件,您将能够了解所有测试失败。这是一个改编自我上面链接的页面的示例:

var Mocha = require('mocha');
var fs = require('fs');
var path = require('path');

var mocha = new Mocha();
var testDir = '.'
fs.readdirSync(testDir).filter(function(file){
    // This gets all files that end with the string test.js (so
    // footest.js, bar_test.js, baz.test.js, etc.
    return file.substr(-7) === 'test.js';
}).forEach(function(file){
    mocha.addFile(path.join(testDir, file));
});

var runner = mocha.run(function(failures){
  process.on('exit', function () {
    process.exit(failures);
  });
});

// This is how we get results.
runner.on('fail', function(test, err){
    console.log(err);
});

Is there for instance a way to check which assertion failed and why, in case of multiple assertions within a test, or receive more information about a specific test, and if yes, how?

Mocha 不提供任何工具将您在 fail 处理程序中通过 err 获得的异常与 特定的 断言相关联。这是因为 Mocha 旨在与您想要的任何断言库一起使用。它仅在捕获失败断言引发的异常时才检测到断言失败。它对成功的断言或未执行的断言一无所知,因为测试在失败的断言上提前结束。您也许可以从堆栈跟踪中进行逆向工程,但 Mocha 不会帮助您实现这一目标。