我正在使用Angular v1.6和Jasmine,我试图通过输入一个输入值来对我们的角度应用程序中的工作指令进行单元测试,但我无法正确启动指令。
指令
.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.有人可以帮助解决如何触发输入变化吗?
答案 0 :(得分:2)
看起来您在element.find('input')
,find
搜索给定元素的子元素时出现问题,因此它不会返回元素本身。因此,所有操作都是在空角元素包装器上进行的。
如果您尝试console.log(dirElementInput.length)
,您会看到此包装器为空。
您可以将其更改为var dirElementInput = element[0];
,测试将通过。