【问题标题】:How to 'reverse' the rejection/fulfillment of a promise?如何“逆转”拒绝/履行承诺?
【发布时间】:2017-11-23 16:55:46
【问题描述】:

对于 mocha 测试,我想断言一个承诺最终会被拒绝。

我不想使用 chai-as-promised。我更喜欢只使用 Node 的标准断言模块,并且只使用标准 ES6 承诺。

我想出的最好的就是这个,但感觉有点hacky:

it('foo should reject given bad data', function () {
  var rejected;

  return foo('bad data').catch(function (err) {
    rejected = true;
  }).then(function () {
    assert(rejected);
  });
});

谁能提出一种更简洁、更有表现力的方式来“撤销”承诺,让拒绝变成满足,反之亦然?

【问题讨论】:

    标签: javascript es6-promise


    【解决方案1】:

    您可以直接通过 truefalse 断言解决和拒绝回调。

    it('foo should reject given bad data', function () {
      return foo('bad data').then(function () {
          assert(false);
      }, function () {
          assert(true);
      });
    });
    

    【讨论】:

      【解决方案2】:

      您可以像这样使用单个 .done() 来做到这一点:

      it('foo should reject given bad data', function () {
        return foo('bad data')
        .done(assert.equal.bind(null, 'false', 'true', null), assert);
      });
      

      我使用了assert.equal 的值,它提供了与assert(false) 等效的值,但如果您想打印实际结果,显然可以删除最后一个null

      编辑:您实际上可以通过定义自己的 assertFail 函数来使这个更清洁以进行多次测试:

      function assertFail () { assert(false); }
      
      it('foo should reject given bad data', function () {
        return foo('bad data')
        .done(assertFail, assert);
      });
      

      【讨论】:

        【解决方案3】:

        您可以在 Promise 原型中添加一个反向方法,然后直接使用它。

        Promise.prototype.reverse = function() {
          return new Promise((resolve, reject) => {
            this.then(reject).catch(resolve);
          });
        }
        
        foo('bad data')
          .reverse()
          .then(e => assert(true))
          .catch(e => assert(false));
        

        【讨论】:

          猜你喜欢
          • 2015-11-16
          • 2017-12-07
          • 1970-01-01
          • 2016-11-07
          • 2014-06-04
          • 2016-06-05
          • 2020-07-30
          • 2019-11-25
          • 2021-03-14
          相关资源
          最近更新 更多