在这个Angular / Jasmine代码中,我有一个控制器和两个服务,service1
和service2
。控制器调用service1
和service1
来电service2
。
我试图在对控制器进行单元测试时模拟service2
,而不是模仿service1
。这可能吗?
这是plunk中我的尝试(不起作用):
angular.module("myModule", [])
.service('service1', function(service2){
this.sum = function(num1,num2) {
return service2.theRealSum(num1,num2);
};
})
.service('service2', function(){
this.theRealSum = function(num1,num2) {
return num1 + num2;
};
})
.controller('ctl', function($scope,$timeout,service1) {
$scope.sumTheTwo = function (num1,num2){
$scope.result = service1.sum(num1,num2);
};
});
describe('Testing a Controller that sums', function () {
var $scope;
beforeEach(module('myModule'));
beforeEach(inject(function($controller, _$rootScope_, service1,service2) {
$scope = _$rootScope_.$new();
spyOn(service2, 'theRealSum');
$controller('ctl', {
$scope: $scope,
service1: service1
});
}));
it('should resolve promise', function () {
$scope.sumTheTwo(1,2);
$scope.$apply();
expect($scope.result).toBe(3);
});
});