Javascript 正在测试将字符串转换为整数的angularjs指令
我一直在测试我的指令:Javascript 正在测试将字符串转换为整数的angularjs指令,javascript,angularjs,testing,directive,Javascript,Angularjs,Testing,Directive,我一直在测试我的指令: angular.module('fooApp') .directive('numericbinding', function () { return { restrict: 'A', require: 'ngModel', scope: { model: '=ngModel', }, link: function (scope, element, attrs)
angular.module('fooApp')
.directive('numericbinding', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: {
model: '=ngModel',
},
link: function (scope, element, attrs) {
scope.$watch(attrs.ngModel, function () {
if (!scope.model) {
// inits with default val
scope.model = 0;
} else if (scope.model && typeof scope.model === 'string') {
// console.log('value changed, new value is: ' + (typeof scope.model));
scope.model = parseInt(scope.model);
// console.log('value changed, new value is: ' + (typeof scope.model));
}
});
}
};
});
单元测试:
'use strict';
describe('Directive: numericbinding', function () {
var $compile;
var $rootScope;
beforeEach(module('fooApp'));
beforeEach(inject(function(_$compile_, _$rootScope_, $httpBackend){
$rootScope = _$rootScope_;
$compile = _$compile_;
$compile('<form name="form1"><input numericbinding ng-model="someModel.Property" name="data"></input></form>')($rootScope);
}));
it('converts string value to integer', inject(function () {
$rootScope.someModel.Property = '10';
// $rootScope.form1.data.$setViewValue('10')
$rootScope.$digest();
expect($rootScope.someModel.Property).toEqual(10);
}));
}
我已经手动进行了测试,string
到integer
的转换工作正常。然而,这个特殊的测试一直失败
知道那个有什么问题吗
更新:
在chrome浏览器中调试显示:
scope.$watch(attrs.ngModel, function () {
调用时未触发:
$rootScope.$digest()代码>在我的测试中。我甚至试过:$rootScope.$apply()
但是这里仍然没有变化。除了PhantomJS之外,你还尝试过其他浏览器吗?@glepretre是的,chrome for Me也有同样的问题。你能尝试改变范围吗?$watch(attrs.ngModel,
by范围。$watch(model,
)以及指令中控制台的输出是否正常?
scope.$watch(attrs.ngModel, function () {