我在这里做错了什么?我有一段看起来像这样的代码:
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);
});
答案 0 :(得分:1)
要查看错误,请暂时更换您的测试:
var rejectionError = new Error("test");
var receivedError;
userServices.getUserList(1).done();
customerDeferred.resolve(customerList);
userDeferred.reject(rejectionError);
这将打印出实际错误。一旦你修复了因拼写错误导致的所有错误,你就会发现它有效。
问题是userRepo
与userRepository
不同,getUsers
与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);
哪个运行得很好。