Reputation: 6005
Is it possible to run Mocha programmatically, yet run it in a "verbose" mode and use the results programmatically?
Right now I am using it in NodeJS via mocha
modules (using chai
internally in the suite for the assertions).
What I want is to get more data about the failed tests than the generic errors of style: "expected true and got false".
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?
Upvotes: 5
Views: 8469
Reputation: 151380
When you run Mocha programmatically, the mocha.run()
method returns a Runner
object. If you listen to fail
events, you'll be able to learn of all test failures. Here's an example adapted from the page I linked to above:
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 does not provide any facility to relate the exception you get through err
in the fail
handler to a specific assertion. This is due to the fact that Mocha is designed to be used with whatever assertion library you want. It only detects that an assertion has failed when it catches the exception raised by the failing assertion. It does not know anything about the assertions that were successful or the assertions that were not executed because the test ended early on the failing assertion. You may be able to reverse engineer something from the stack trace but Mocha won't help you towards this goal.
Upvotes: 3