使用带有 chai-as-promised 的自定义 chai 方法断言

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

我想添加这样的自定义 assertion/method:

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

但是我希望能够像这样将它与 chai-as-promised 一起使用:

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

但是当我 运行 这个例子时,我看到这个错误:

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

这是因为 chai-as-promised 在将其传递给 convertToStringEqual 之前没有用 eventually 解决该承诺。

在将它传递给我的自定义断言方法之前,如何获得 chai-as-promised 等待该承诺?

首先加载您的自定义插件,然后添加 chai-as-promise。与加载插件的顺序有关。

来自#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.

例如

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

单元测试结果:

  65418901
    ✓ should pass


  1 passing (52ms)

但是,这样加载插件是行不通的:

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