0

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

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

1 回答 1

1

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

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

userServices.getUserList(1).done();

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

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

问题是userRepo不同于userRepositorygetUsers不同getUserList

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

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

运行完美。

于 2013-05-17T13:44:35.217 回答