【问题标题】:Why does my Q chained promise rejection not behave the way I expect?为什么我的 Q 链式承诺拒绝不符合我的预期?
【发布时间】:2013-05-11 21:09:43
【问题描述】:

我在这里做错了什么?我有一段看起来像这样的代码:

function getUserList(requestingUserId){
  return customerRepo.getCustomersAllowedByUser(requestingUserId)
  .then(function(customers){
    return userRepo.getUserList({customers: customers});
  });
}

我的存储库代码如下所示:

customerDeferred = q.defer();
userDeferred = q.defer();

customerRepository.getCustomersAllowedByUser = sinon.stub().returns(customerDeferred.promise);
userRepository.getUsers = sinon.stub().returns(userDeferred.promise);

当两个承诺都得到解决时,一切正常,当我拒绝客户承诺时,正如预期的那样,但是当我解决客户承诺并拒绝用户承诺时,测试就会失败。这是测试:

it('should forward the rejection when userRepository rejects the promise', function(done){
  var rejectionError = new Error("test");
  var receivedError;

  userServices.getUserList(1)
  .then(null, function(error){
    receivedError = error;
  })
  .fin(function(){
    receivedError.should.equal(rejectionError);
    done();
  });

  customerDeferred.resolve(customerList);
  userDeferred.reject(rejectionError);
});

【问题讨论】:

  • 它是如何分解的?

标签: node.js mocha.js promise q


【解决方案1】:

要查看有什么问题,请将您的测试暂时替换为:

var rejectionError = new Error("test");
var receivedError;

userServices.getUserList(1).done();

customerDeferred.resolve(customerList);
userDeferred.reject(rejectionError);

这将打印出实际的错误。一旦你修复了所有由拼写错误导致的错误,你会发现它有效。

问题是userRepouserRepository 不同,getUsersgetUserList 不同。

解决了所有这些问题,我最终得到了:

var q = require('q')
var sinon = require('sinon')

var assert = require('assert')

customerDeferred = q.defer();
userDeferred = q.defer();

var customerList = []
var customerRepo = {}
var userRepo = {}

customerRepo.getCustomersAllowedByUser = sinon.stub().returns(customerDeferred.promise);
userRepo.getUsers = sinon.stub().returns(userDeferred.promise);

function getUserList(requestingUserId){
  return customerRepo.getCustomersAllowedByUser(requestingUserId)
  .then(function(customers){
    return userRepo.getUsers({customers: customers});
  });
}

var rejectionError = new Error("test");
var receivedError;

getUserList(1)
.then(null, function(error){
  receivedError = error;
})
.fin(function(){
  assert.equal(receivedError, rejectionError);
  console.log('DONE')
});

customerDeferred.resolve(customerList);
userDeferred.reject(rejectionError);

完美运行。

【讨论】:

  • 是的,我在发帖后就知道了。感谢 .done() 的提示
猜你喜欢
  • 2013-01-28
  • 1970-01-01
  • 2019-11-25
  • 2018-07-04
  • 2013-09-16
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多