我有以下创建input
元素的AngularJS指令。输入具有运行doIt()
函数的ng-change
属性。在我的指令的单元测试中,我想检查当用户更改输入时是否调用了doIt
函数。但是测试没有通过。尽管它在浏览器中手动测试时可以正常工作。
指令:
...
template: "<input ng-model='myModel' ng-change='doIt()' type='text'>"
测试:
el.find('input').trigger('change') // Dos not trigger ng-change
实时演示(ng-change):http://plnkr.co/edit/0yaUP6IQk7EIneRmphbW?p=preview
现在,如果我手动绑定change
事件而不是使用ng-change
属性,测试就会通过。
template: "<input ng-model='myModel' type='text'>",
link: function(scope, element, attrs) {
element.bind('change', function(event) {
scope.doIt();
});
}
实时演示(手动绑定):http://plnkr.co/edit/dizuRaTFn4Ay1t41jL1K?p=preview
有没有一种方法可以使用ng-change
并使其可测试?谢谢。
发布于 2016-09-06 05:54:54
我在谷歌上搜索了"angular directive trigger ng-change“,这个StackOverflow问题是我最接近有用的问题,所以我会回答”如何在指令中触发ng-change“,因为其他人肯定会出现在这个页面上,而我不知道如何提供这些信息。
在指令的link函数中,这将在您的元素上触发ng-change函数:
element.controller('ngModel').$viewChangeListeners[0]();
element.trigger("change")
和element.trigger("input")
对我不起作用,我在网上能找到的其他东西也不起作用。
例如,在模糊上触发ng-change:
wpModule.directive('triggerChangeOnBlur', function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.on('blur', function () {
element.controller('ngModel').$viewChangeListeners[0]();
});
}
};
}]);
很抱歉,这没有直接回答OP的问题。我将非常乐意接受一些关于在哪里以及如何分享这些信息的合理建议。
发布于 2017-05-19 17:05:37
很简单,它可以在你的单元测试环境中工作:
spyOn(self, 'updateTransactionPrice');
var el = compile('<form name="form" latest novalidate json-schema="main.schema_discount" json-schema-model="main._data"><input type="text" ng-model="main._data.reverse_discount" ng-class="{ \'form-invalid\': form.reverse_discount.$invalid }" ng-change="main.transactionPrice(form);" name="reverse_discount" class="form-control-basic" placeholder="" ng-disabled="!main.selectedProduct.total_price"></form>')(scope);
el.find('input').triggerHandler('change');
expect(self.updateTransactionPrice).toHaveBeenCalled();
发布于 2016-03-31 00:55:35
我花了很长时间才找到这条简单的线。只是为了把它保存在这里。
如何使用Karma从html-select中选择值,从而使ng-change函数正常工作?
HTML:
控制器或指令JS:
$scope.itemTypes = [{name: 'Some name 1', value: 'value_1'}, {name: 'Some name 2', value: 'value_2'}]
$scope.itemTypeSelected = function () {
console.log("Yesssa !!!!");
};
Karma测试片段:
angular.element(element.find("#selectedItemType")[0]).val('value_1').change();
console.log("selected model.selectedItemType", element.isolateScope().model.selectedItemType);
控制台:
'Yesssa !!!!'
'selected model.selectedItemType', 'value_1'
https://stackoverflow.com/questions/17626604
复制相似问题