I'm using mocha
and chai
as assertions.
I have several assertions in my spec:
Exp1.should.be.true
Exp2.should.be.true
Exp3.should.be.true
If one of them fails mocha writes "expected false to be true". Is there a way to identify them?
With expect
I can do it:
expect(Exp1, 'Exp1').to.be true
Is something like this possible with should
?
Usually, to perform automated tests, you'll need a testing library. Mocha is one such library. You can test one or more methods in your JavaScript code with Mocha. Assertions are a key part of writing automated tests with a tool like Mocha. They do the job of verifying that a piece of code returns the expected result.
Chai assertion library is an external javascript library used to write assertions. Compared to what we write directly in javascript, this assertion library needs less time & effort and easy use. Chai assertion library is available by default in the Postman.
It is a highly customizable framework that supports different assertions and libraries. Chai is an assertion library that is mostly used alongside Mocha. It can be used both as a BDD / TDD assertion library for NodeJS and can be paired with any JavaScript testing framework.
Chai is such an assertion library, which provides certain interfaces to implement assertions for any JavaScript-based framework. Chai's interfaces are broadly classified into two: TDD styles and BDD styles.
Apparently should
does not support custom error messages at the moment.
You can create your own helper for setting the message:
var chai = require('chai'),
should = chai.should();
// Helper definition - should be in a shared file
chai.use(function(_chai, utils) {
_chai.Assertion.addMethod('withMessage', function(msg) {
utils.flag(this, 'message', msg);
});
});
// Sample usage
it('should fail', function() {
var Exp1 = false;
var Exp2 = false;
Exp1.should.be.withMessage('Exp1').true;
Exp1.should.withMessage('Exp2').be.true;
});
I checked the chai code with respect to should and found that the currently accepted answer is either incorrect or incomplete.
If you read there, you will find that there is indeed a way to include your own custom message in each assertion. The catch is that you may need to change your assertion syntaxes to use should
's function calls instead.
(1).should.equal(0, 'This should fail');
/****** Output with (I believe) default reporter *****
* This should fail
* + expected - actual
*
* -1
* +0
*/
Note that your output may look different if you are using your own reporter. If you feel so inclined, you could probably wrap should
's functions to always include line number in your assertion output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With