【发布时间】:2016-07-27 06:18:35
【问题描述】:
在下面的 SampleController 中,我如何对 postAttributes 函数调用 sampleService.updateMethod。由于 updateMethod 返回了 promise,我遇到了麻烦。
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
});
}
};
}
我想在控制器规范中模拟工厂服务,而不是将实际服务直接注入 $controller,因为大多数单元测试指南都指定在隔离下测试单元。
示例控制器规格:
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??
});
});
【问题讨论】:
标签: angularjs unit-testing jasmine angularjs-factory angular-mock