【问题标题】:Unit testing bluebird promise bind function单元测试蓝鸟承诺绑定功能
【发布时间】:2017-08-10 15:30:21
【问题描述】:

我有以下函数,它使用bind 将上下文绑定到then 链。当我尝试测试它时,它会抛出

  TypeError: redisClient.hgetallAsync(...).bind is not a function


myFunc() {
    let self = this;

    return redisClient.hgetallAsync('abcde')
      .bind({ api: self })
      .then(doStuff)
      .catch(err => {
        // error
      });
  }

测试

let redisClient = { hgetallAsync: sinon.stub() };

describe('myFunc', () => {
    beforeEach(() => {
      redisCLient.hgetallAsync.resolves('content!');
    });

    it('should do stuff', () => {
      return myFunc()
        .should.eventually.be.rejectedWith('Internal Server Error')
        .and.be.an.instanceOf(Error)
        .and.have.property('statusCode', 500);
    });
  });

【问题讨论】:

    标签: unit-testing bluebird sinon sinon-chai


    【解决方案1】:

    hgetallAsync 存根返回一个普通的 JS Promise 而不是 Bluebird 承诺。

    要使用Bluebird 承诺,您需要使用.usingPromise() 告诉Sinon 这样做。

    let redisClient = { hgetallAsync: sinon.stub().usingPromise(bluebird.Promise) };
    

    文档链接: http://sinonjs.org/releases/v4.1.2/stubs/#stubusingpromisepromiselibrary

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-19
      • 1970-01-01
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 2014-02-13
      相关资源
      最近更新 更多