我有一个 Controller ,它只是监视“名称”属性并在发生任何更改时打印其新值和旧值。
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。为什么旧值丢失了?
最佳答案
我认为,这就是行为。当我们第一次调用 Controller 时,旧值等于新值,因此什么也没有发生。一般在这种情况下我们可以这样写:
if(oldValue === newValue){return;}
我们也可以这样写$watch
:
$scope.$watch('name', function () {
// ....
});
并且仅当 name
更改时才会调用:
演示 1 Plunker
我不是 Unitest Guru,无论如何尝试一下这个流程:
Controller
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
关于javascript - 在单元测试中观察 AngularJS 属性时,newValue 始终等于 oldValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20633207/