gpt4 book ai didi

javascript - 在单元测试中监视 AngularJS 属性中的 newValue 始终等于 oldValue

转载 作者:行者123 更新时间:2023-11-29 16:13:53 28 4
gpt4 key购买 nike

我有一个 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);
});

联合测试

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com