testing an angular checkbox using in jasmin

℡╲_俬逩灬. 提交于 2020-01-03 10:44:54

问题


My situation is as follows:

directive

scope: { foo:'=' },
template: '<input type="checkbox" ng-model="foo"/>'

parent controller

$scope.foo = false;

jasmine test

var cb = iElement.find('input');

$timeout(function() {  // using $timeout to ensure $digest() isn't the issue.
    cb.prop('checked',!cb.prop('checked'))
},0);

expect(cb.prop('checked')).toBe(true); // passes

expect($scope.foo).toBe(true); // doesn't pass

My question: why doesn't $scope.foo get updated when I issue the prop('checked') even though the DOM does (as I've verified after inspecting it).

Here is a jsbin that roughly demonstrates the problem http://jsbin.com/kapifezi/2/edit


回答1:


So the complete answer would be: You need to change 'checked' property, and then trigger click event.

var input = element.find('input');
input.prop('checked',!input.prop('checked'));
// input.triggerHandler('click');
input.triggerHandler('change');

Thanks Kevin, that helped me a lot!




回答2:


After further investigation - it looks like angular will add a click listener when you add an ng-model to something like a checkbox.

So it would seem that the correct method of testing this would be to issue a click event on the DOM object from within the jasmine test.




回答3:


try

expect($scope.$parent.foo).toBe(true);

updating answer:

$timeout(function() {  // using $timeout to ensure $digest() isn't the issue.
      //cb.prop('checked',!cb.prop('checked'));  
      $scope.val = !cb.prop('checked');

},0);

you want to keep all updates on the scope level and let angular manage the cycles by itself. if updated the property you're off angular's radar.



来源:https://stackoverflow.com/questions/22774995/testing-an-angular-checkbox-using-in-jasmin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!