测试这样的函数:
beforeEach(inject(function($rootScope, $controller, $injector){
service = $injector.get('service');
scope = $rootScope.$new();
createController = function() {
return $controller('mainCtrl', {
'$scope': scope
});
};
}));
$scope.$watch('value', function(newVal, oldVal) {
if(newVal != oldVal)
service.setValue(newVal);
});
通过这样的测试:
it("$watch value",function(){
spyOn(service,'setValue').andCallThrough();
var controller=createController();
scope.value = true;
expect(service.setValue).toHaveBeenCalled();
})
由于这种情况,间谍永远不会被触发。 如何使用参数触发此监视事件以测试是否调用了服务?
答案 0 :(得分:0)
请进行以下更改:
您需要使用scope.$apply();
更新绑定和contoller as
语法以获取controller.value
;
虽然定义控制器使用这个而不是范围,但变量在Jasmine中很容易获得。
Jasmine脚本:
describe("test", function() {
var Service, scope, controller;
beforeEach(module('inspinia'));
beforeEach(inject(function($rootScope, $controller, $injector, serviceData) {
Service = serviceData;
scope = $rootScope.$new();
controller = $controller('mainCtrl as ctrl', {
$scope: scope
});;
}));
it("$watch value", function() {
spyOn(Service,'setValue').and.callThrough();
controller.value = 1120;
scope.$apply();
controller.value = 1121;
scope.$apply();
expect(Service.setValue).toHaveBeenCalled();
})
})
Angular script :
(function() {
'use strict';
angular.module('inspinia', [])
.controller('mainCtrl', function($scope, serviceData) {
var ctrl = this;
ctrl.value = 1230;
$scope.$watch('ctrl.value', function(newVal, oldVal) {
if (newVal != oldVal) {
console.log(newVal, oldVal, newVal !== oldVal);
serviceData.setValue(newVal);
}
});
})
.factory('serviceData', function() {
var obj = {};
obj.setValue = function() {
console.log(1010)
}
return obj;
});
})();