我有一个看起来像的函数:
$scope.setUserWatch = function(userName){
$scope.clearUserWatchs[userName] = $scope.$watch('user["' + userName + '"].value', function(newValue, oldValue){
if(newValue != oldValue){
if(newValue === false){
$scope.customFunction(userName);
}
}
});
}
上述功能允许我根据命令设置特定$scope
变量value
键的监视。设置好手表后,我也可以拨打$scope.clearUserWatchs
的财产来移除手表。
我对以上功能进行了以下测试:
describe('setUserWatch Test', function(){
it('should call scope.customFunction()', function(){
var userName = 'tank';
scope.user = {};
scope.user[userName] = {
value: false
};
spyOn(scope, 'customFunction');
scope.setUserWatch(userName);
scope.$apply();
expect(scope.customFunction).toHaveBeenCalledWith(userName);
});
});
当我运行上述测试时,$scope.$watch()
的回调函数中没有任何操作发生。在传统的$scope.$watch()
测试中(手表未封装到外部函数中),具有正确相应变量更改的scope.$apply
将触发回调。
这里需要做些什么来测试这款手表?
答案 0 :(得分:-1)
这是我在命令函数上测试$watch()
时需要做的事情:
describe('setUserWatch Test', function(){
it('should call scope.customFunction()', function(){
scope.user = {
autumn: {
value: true
}
};
scope.$apply();
scope.clearSeenWatchs = {};
scope.user = {
autumn: {
value: false
}
};
spyOn(scope, 'customFunction');
scope.setUserWatch('autumn');
scope.$apply();
expect(scope.customFunction).toHaveBeenCalled();
});
});
第一个scope.$apply()
为监视变量赋值true
。第二个scope.$apply()
的值为false
。这样就可以同时满足newValue != oldValue
回调中的newValue === false
和$watch
条件。
答案 1 :(得分:-1)
它不能以这种方式工作,因为简短的测试可以证明它。
angular.module('app', [])
.controller('UserCtrl', function($scope) {
$scope.clearUserWatchs = {}
$scope.customFunction = function(name) {};
$scope.setUserWatch = function(userName) {
$scope.clearUserWatchs[userName] = $scope.$watch('user["' + userName + '"].value', function(newValue, oldValue) {
if (newValue != oldValue) {
if (newValue === false) {
$scope.customFunction(userName);
}
}
});
}
});
describe('User', function() {
beforeEach(module('app'));
var scope, UserCtrl
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new()
UserCtrl = $controller('UserCtrl', {
$scope: scope
})
}));
describe('setUserWatch Test', function() {
it('true', function() {
var userName = 'tank';
scope.user = {};
scope.user[userName] = {
value: false
};
spyOn(scope, 'customFunction');
scope.setUserWatch(userName);
scope.$apply();
expect(scope.customFunction).toHaveBeenCalledWith(userName);
})
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-mocks.js"></script>