Chai, Mocha: Identify should assertion

£可爱£侵袭症+ 提交于 2019-12-13 13:10:21

问题


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?


回答1:


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



回答2:


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.




回答3:


I wonder why they don't simply add which line fired the assertion, but I ran into this exact same problem myself. A colleague who can manuals better than I noted there is a setting for includeStack which will give line numbers for assertions. http://chaijs.com/guide/styles/#configure

Since I'm doing a lot of async, I might run my tests in before or beforeEach and then run a separate it for each assertion.



来源:https://stackoverflow.com/questions/11527474/chai-mocha-identify-should-assertion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!