简体   繁体   English

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

[英]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:但是我希望能够将它与chai-as-promised一起使用,如下所示:

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 .这是因为chai-as-promised在将其传递给convertToStringEqual之前eventually没有解决 promise 。

How can I get chai-as-promised await that promise before passing it to my custom assertion method?在将 promise 传递给我的自定义断言方法之前,我如何才能chai-as-promised等待 promise?

Load your custom plugin firstly, then, add the chai-as-promise .首先加载您的自定义插件,然后添加chai-as-promise Related to the order of loading plugins.与加载插件的顺序有关。

From the #installation-and-setup#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.使用其他 Chai 插件时请注意:Chai as Promised 会在安装时查找所有当前注册的断言器并承诺它们。 Thus, you should install Chai as Promised last , after any other Chai plugins, if you expect their asserters to be promisified.因此,如果您希望他们的断言器被承诺,您应该在任何其他 Chai 插件之后安装 Chai 作为 Promised last

Eg例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM