我有一个控制器,它只是看一个'name'属性,并在任何变化时打印它的新旧值。
function Ctrl($scope) {
$scope.$watch('name', function(newValue, oldValue) {
console.log('newValue: ' + newValue + ', oldValue: '+ oldValue);
if (newValue !== oldValue) {
//...
}
}
});
然后我想用Jasmine进行单元测试:
var rootScope, scope, ctrl;
beforeEach(inject(function ($rootScope, $controller) {
rootScope = $rootScope;
scope = $rootScope.$new();
ctrl = $controller('Ctrl', { $scope: scope });
}));
it('should have different old and new values if I set a new name', function() {
rootScope.name = 'some new name';
rootScope.$apply();
//expect the behaviors happen for newValue !== oldValue
});
然后我希望控制台记录一条消息,指示newValue不等于oldValue,但是我总是得到newValue === oldValue。为什么旧的价值会丢失?
答案 0 :(得分:4)
我所做的是在创建控制器后立即在beforeEach子句中运行摘要:
beforeEach(inject(function ($rootScope, $controller) {
rootScope = $rootScope;
scope = $rootScope.$new();
ctrl = $controller('Ctrl', { $scope: scope });
scope.$digest();
}));
这样,摘要在运行每个测试之前完成,手表正常工作。
答案 1 :(得分:2)
我认为,这就是行为。当我们第一次调用控制器时,旧值等于新值,因此没有任何反应。通常在这种情况下我们可以写:
if(oldValue === newValue){return;}
我们也可以像$watch
那样写:
$scope.$watch('name', function () {
// ....
});
仅在name
发生更改时才会调用它:
演示1 Plunker
我不是Unitest Guru,无论如何都试试这个流程:
<强>控制器强>
angular.module('plunker').controller('MyCtrl', function($scope) {
$scope.watchFunctionCounter= 0;
$scope.$watch(function () {
return $scope.name;
},
function (newValue, oldValue) {
console.log('newValue: ' + newValue + ', oldValue: '+ oldValue);
if (newValue !== oldValue) {
$scope.watchFunctionCounter++;
}
}, true);
});
<强> UNITEST 强>
describe('Directive: maybeLink', function() {
var scope, ctrl;
beforeEach(function() {
module('plunker');
inject(function($rootScope, $controller) {
scope = $rootScope.$new();
ctrl = $controller('MyCtrl', {$scope: scope});
});
});
afterEach(function() {
controller = null;
});
it('should have different old and new values if I set a new name', function() {
scope.name = 'some new name';
scope.$digest();
expect(scope.watchFunctionCounter).toBe(0);
// on this strage the name is undefined, therefore we stay out of "if" statemant
scope.name = 'diff name';
scope.$digest();
expect(scope.watchFunctionCounter).toBe(1);
});
});
演示2 Plunker