AngularJS 带输入的单元测试指令
AngularJS Unit Test Directive with Input
我正在将 Angular v1.6 与 Jasmine 一起使用,我正在尝试通过输入输入值对我们的 angular 应用程序中的工作指令进行单元测试,但我无法让指令触发正确。
指令
.directive('percentage', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
function fromUser(value) {
return value / 100;
}
function toUser(value) {
return Math.round(value * 100);
}
ngModel.$parsers.push(fromUser);
ngModel.$formatters.push(toUser);
}
};
})
单元测试
describe('percentageDirective', function() {
beforeEach(module('app'));
// Inject $rootScope and $compile
var scope, element;
beforeEach(inject(function($rootScope, $compile) {
// Set up the scope with test data
scope = $rootScope.$new();
scope.value = 0;
// Create an element
element = angular.element('<input type="number" percentage ng-model="value"></input>');
// Compile that element with your scope
element = $compile(element)(scope);
// Run the digest cycle to compile the element
$rootScope.$digest();
// Find the input control:
var dirElementInput = element.find('input');
// Set some text
angular.element(dirElementInput).val('25').triggerHandler('input');
scope.$apply();
}));
it("should display the decimal value", function() {
expect(scope.value).toEqual('0.25');
});
});
范围值永远不会改变并保持为 0。有人可以帮助解决如何触发输入更改吗?
您似乎遇到了 element.find('input')
问题,find
搜索给定元素的子元素,结果 return 不会搜索元素本身。因此,您的所有操作都是在一个空的 angular 元素包装器上进行的。
如果你尝试 console.log(dirElementInput.length)
你会发现这个包装是空的。
您可以将其更改为 var dirElementInput = element[0];
,测试将通过。
我正在将 Angular v1.6 与 Jasmine 一起使用,我正在尝试通过输入输入值对我们的 angular 应用程序中的工作指令进行单元测试,但我无法让指令触发正确。
指令
.directive('percentage', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
function fromUser(value) {
return value / 100;
}
function toUser(value) {
return Math.round(value * 100);
}
ngModel.$parsers.push(fromUser);
ngModel.$formatters.push(toUser);
}
};
})
单元测试
describe('percentageDirective', function() {
beforeEach(module('app'));
// Inject $rootScope and $compile
var scope, element;
beforeEach(inject(function($rootScope, $compile) {
// Set up the scope with test data
scope = $rootScope.$new();
scope.value = 0;
// Create an element
element = angular.element('<input type="number" percentage ng-model="value"></input>');
// Compile that element with your scope
element = $compile(element)(scope);
// Run the digest cycle to compile the element
$rootScope.$digest();
// Find the input control:
var dirElementInput = element.find('input');
// Set some text
angular.element(dirElementInput).val('25').triggerHandler('input');
scope.$apply();
}));
it("should display the decimal value", function() {
expect(scope.value).toEqual('0.25');
});
});
范围值永远不会改变并保持为 0。有人可以帮助解决如何触发输入更改吗?
您似乎遇到了 element.find('input')
问题,find
搜索给定元素的子元素,结果 return 不会搜索元素本身。因此,您的所有操作都是在一个空的 angular 元素包装器上进行的。
如果你尝试 console.log(dirElementInput.length)
你会发现这个包装是空的。
您可以将其更改为 var dirElementInput = element[0];
,测试将通过。