mocha.jsshould.jschai

Chai, Mocha: Identify should assertion


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?


Solution

  • 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;
    });