Reputation: 2288
If I use mocha.js with dynamically generated tests, then how do I print out context of what were variable values when test failed?
If we take that example from mocha.js documentation,
var assert = require('assert');
function add() {
return Array.prototype.slice.call(arguments).reduce(function(prev, curr) {
return prev + curr;
}, 0);
}
describe('add()', function() {
var tests = [
{args: [1, 2], expected: 3},
{args: [1, 2, 3], expected: 6},
{args: [1, 2, 3, 4], expected: 10}
];
tests.forEach(function(test) {
it('correctly adds ' + test.args.length + ' args', function() {
var res = add.apply(null, test.args);
assert.equal(res, test.expected);
});
});
});
then how do I print out {args: [1, 2, 3], expected: 6},
if second test fails?
Upvotes: 0
Views: 297
Reputation: 3268
you can add an additional parameter message
to the assert.XYZ methods which will be output when the assert fails. You can add your desired output there
tests.forEach(function(test) {
it('correctly adds ' + test.args.length + ' args', function() {
var res = add.apply(null, test.args);
assert.equal(res, test.expected, "Failed with data " + JSON.stringify(test));
});
});
Upvotes: 1
Reputation: 7438
You can pass additional comments as third argument for assert
method
tests.forEach(function(test) {
it('correctly adds ' + test.args.length + ' args', function() {
var res = add.apply(null, test.args);
assert.equal(res, test.expected, JSON.stringify(test)); // third argument passed
});
});
will produce output like:
1) add() correctly adds 3 args: AssertionError: {"args":[1,2,3],"expected":8} + expected - actual -6 +8
Upvotes: 1