How to test behavior in the link function of a directive

后端 未结 5 1571
清酒与你
清酒与你 2020-12-23 19:55

In some of my directives, I\'m adding functions to the scope to handle logic specific for the directive. For example:

link: function(scope, element, attrs) {         


        
5条回答
  •  悲&欢浪女
    2020-12-23 20:08

    I resolved this issue a bit differently.

    If you have a very simple link function in your directive and you don't happen to need the 3rd argument(attrs), just get rid of the link function and assign the directive a controller instead.

    app.directive('loadIndicator', function() {
      return {
        restrict: 'E',
        replace: true,
        templateUrl: 'blahblah/indicator.html',
        controller: 'LoadIndicatorController'
      };
    });
    

    just as you have the args for scope and element in a directive's link function, these 2 args can be injected into an easy-to-test controller as $scope and $element.

    If you are capable of creating controllers and unit testing those controllers, then this will be really easy to do.

提交回复
热议问题