Search code examples
javascripttestingmocha.jschaichai-as-promised

Using a custom chai method assertion with chai-as-promised


I want to add a custom assertion/method like this:

chai.use(function (chai, utils) {
  var Assertion = chai.Assertion;
  Assertion.addMethod("convertToStringEqual", function (input) {
    new Assertion(this._obj.toString()).to.equal(input.toString());
  });
});

However I want to be able to use it with chai-as-promised like so:

Promise.resolve(2 + 2).should.eventually.convertToStringEqual(4);

But when I run this example, I see this error:

AssertionError: expected '[object Promise]' to equal '4'

This is because chai-as-promised is not resolving that promise with eventually before passing it to convertToStringEqual.

How can I get chai-as-promised await that promise before passing it to my custom assertion method?


Solution

  • Load your custom plugin firstly, then, add the chai-as-promise. Related to the order of loading plugins.

    From the #installation-and-setup

    Note when using other Chai plugins: Chai as Promised finds all currently-registered asserters and promisifies them, at the time it is installed. Thus, you should install Chai as Promised last, after any other Chai plugins, if you expect their asserters to be promisified.

    E.g.

    const chai = require('chai');
    const chaiAsPromised = require('chai-as-promised');
    
    chai.use(function(chai, utils) {
      var Assertion = chai.Assertion;
      Assertion.addMethod('convertToStringEqual', function(input) {
        new Assertion(this._obj.toString()).to.equal(input.toString());
      });
    });
    chai.use(chaiAsPromised);
    chai.should();
    
    describe('65418901', () => {
      it('should pass', () => {
        return Promise.resolve(2 + 2).should.eventually.convertToStringEqual(4);
      });
    });
    

    unit test result:

      65418901
        ✓ should pass
    
    
      1 passing (52ms)
    

    But, load the plugins like this will not work:

    chai.use(chaiAsPromised);
    chai.use(function(chai, utils) {
      var Assertion = chai.Assertion;
      Assertion.addMethod('convertToStringEqual', function(input) {
        new Assertion(this._obj.toString()).to.equal(input.toString());
      });
    });
    chai.should();