gpt4 book ai didi

angularjs - 如何使用 jasmine 在 Angular 上测试 $parsers.push 和 $formatters.push

转载 作者:行者123 更新时间:2023-11-28 19:53:15 26 4
gpt4 key购买 nike

我不能强制 Angular 在更新输入时触发 $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, 1000, 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');

});
});
});

最佳答案

摘自阿科斯塔评论中的视频:

使 Angular 发挥作用的方法是触发元素上的“输入”事件(使用 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');

关于angularjs - 如何使用 jasmine 在 Angular 上测试 $parsers.push 和 $formatters.push,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20374089/

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