在下面的工厂服务SampleController,我怎么单元测试postAttributes函数调用sampleService .update方法。自updateMethod返回诺言以来,我遇到了麻烦。如何单元测试(使用茉莉花)在控制器中的函数调用,它返回一个承诺
angular.module('sampleModule')
.controller('SampleController', SampleController);
SampleController.$inject =['sampleService'];
function SampleController(sampleService){
this.postAttributes = function() {
sampleService.updateMethod(number,attributes)
.then(function(response){
//do something on successful update
},function(response){
//do something on unsuccessful update
});
};
}
这里是工厂的服务,我有:
angular.module('sampleModule')
.factory('sampleService', sampleService);
sampleService.$inject = ['$http'];
function sampleService($http) {
return {
getMethod: function(acctNumber){
return $http({
method: 'GET',
url: //api endpoint
});
},
updateMethod: function(number, attributes){
return $http({
method: 'PUT',
url: //api endpoint,
data: //payload
});
}
};
}
我想嘲笑控制器规范的工厂服务,而不是直接注入实际的服务为$控制器,因为大多数单位测试指南指定在隔离状态下测试一个单元。
样品控制器规格:
describe('SampleController Test', function(){
var $controller;
var service;
beforeEach(angular.mock.module('sampleModule'));
beforeEach(angular.mock.inject(function(_$controller_){
$controller = _$controller_;
}));
it('Testing $scope variable', function(){
var sampleController = $controller('SampleController', {
sampleService: service, //mocked factory service
});
sampleController.postAttributes(); //calling the function first
//here I would like to make an assertion to check if
//sampleService.updateMethod has been called with certain parameters
//how do I do that??
});
});
尝试了上述方法,但后来发现** sampleService **本身具有很多依赖性。因此,如果我必须遵循上述方法,那么我需要注入sampleService的所有依赖关系,应该是这种情况,因为我们测试的只是控制器,我们应该嘲笑所有的依赖关系。目前我试图用$ provide.factory来模拟服务。我该如何从成功和错误模块的模拟服务中返回承诺? – Pramodh
我不知道为什么你还需要注入服务的依赖关系。我从来没有这样做,我的一些服务也有一些依赖。在任何情况下,您都可以使用deferred.resolve()命中您的成功块,并使用deferred.reject()命中您的错误块。 – tehbeardedone