angularjs – 如何使用jasmine测试角度为$parsers.push和$format
发布时间:2020-12-17 17:12:58 所属栏目:安全 来源:网络整理
导读:在更新输入时我无法强制角度来解析$parsers.push,所以在上面的测试中使用此指令,你如何触发$parsers.push? mainApp.directive('amountConverter',function() { return { restrict: 'A',require: 'ngModel',link: function(scope,element,attrs,ngModelContr
在更新输入时我无法强制角度来解析$parsers.push,所以在上面的测试中使用此指令,你如何触发$parsers.push?
mainApp.directive('amountConverter',function() { return { restrict: 'A',require: 'ngModel',link: function(scope,element,attrs,ngModelController) { var isInt = function(value) { return !isNaN(parseInt(value,10)) && (parseFloat(value,10) == parseInt(value,10)); },convert = function(initial,multiplier,text) { var amount = text.replace(initial,""); if (!isInt(amount)) { throw " Amount not a number"; } return amount * multiplier; }; //convert data from view format to model format ngModelController.$parsers.push(function(value) { if (value === null || value === undefined) { return null; } var text = value.toUpperCase(); var amount = 0; var initial = text.substring(text.length - 1); if (initial === "B") { amount = convert(initial,1000000000,text); } else if (initial === "M") { amount = convert(initial,1000000,text); } else if (initial === "K") { amount = convert(initial,1000,text); } else if (initial === "T") { amount = convert(initial,text); } else { return value; } element[0].value = amount; return amount; //converted }); } }; }); describe('Directives',function () { var element,scope; beforeEach(module('mainApp')); beforeEach(inject(function ($compile,$rootScope) { scope = $rootScope; element = angular.element('<input type="text" data-ng-model="Amount" amount-Converter/>'); $compile(element)(scope); scope.$digest(); })); //////Jasmine Test describe('amountConverter',function () { it('should return change element state after click to be visible',function () { element.scope().Amount = '10k'; element.scope().$apply(); expect(element[0].value).toBe('10000'); }); }); }); 解决方法
摘自Acosta评论中的视频:
使角度做的事情的方法是触发元素上的’input’事件(使用element.trigger(‘input’).所以在你的测试中,你应该能够做到: element.val("10k"); element.trigger("input"); element.scope().$apply(); //not sure if you even need to do this,video says yes,however on angular 1.3.8 I didnt need to expect(element.val()).toBe('10000'); expect(element.scope().Amount).toBe('10000'); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |