How to trigger ng-change in directive test in AngularJS

后端 未结 5 1056
情歌与酒
情歌与酒 2021-01-01 15:13

I have the following AngularJS directive that creates an input element. Input has ng-change attribute that runs doIt() function. In my

5条回答
  •  爱一瞬间的悲伤
    2021-01-01 15:48

    From your explanatory comment:

    All I want to do in directive's test is to check that doIt is called when user changes the input.

    Whether or not the expression indicated by ng-change is correctly evaluated or not is really the responsibility of the ngModel directive, so I'm not sure I'd test it in this way; instead, I'd trust that the ngModel and ngChange directives have been correctly implemented and tested to call the function specified, and just test that calling the function itself affects the directive in the correct manner. An end-to-end or integration test could be used to handle the full-use scenario.

    That said, you can get hold of the ngModelController instance that drives the ngModel change callback and set the view value yourself:

    it('trigger doIt', function() {
      var ngModelController = el.find('input').controller('ngModel');
      ngModelController.$setViewValue('test');
      expect($scope.youDidIt).toBe(true);
    });
    

    As I said, though, I feel like this is reaching too far into ngModel's responsibilities, breaking the black-boxing you get with naturally composable directives.

    Example: http://plnkr.co/edit/BaWpxLuMh3HvivPUbrsd?p=preview


    [Update]

    After looking around at the AngularJS source, I found that the following also works:

    it('trigger doIt', function() {
      el.find('input').trigger('input');
      expect($scope.youDidIt).toBe(true);
    });
    

    It looks like the event is different in some browsers; input seems to work for Chrome.

    Example: http://plnkr.co/edit/rbZ5OnBtKMzdpmPkmn2B?p=preview

    Here is the relevant AngularJS code, which uses the $sniffer service to figure out which event to trigger:

    changeInputValueTo = function(value) {
      inputElm.val(value);
      browserTrigger(inputElm, $sniffer.hasEvent('input') ? 'input' : 'change');
    };
    

    Even having this, I'm not sure I'd test a directive in this way.

提交回复
热议问题