最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Unit Testing private functions in AngularJS Directive - Stack Overflow

programmeradmin6浏览0评论

How do I unit test a function that is defined inside a directive like the following myFunc?

angular.module('myApp')
  .directive('myDir', [function () {

    var myFunc = function (arg) {
      // code in here.
    };

    return {
      restrict: 'A',
      scope: { },
      link: function (scope, element) {

      }
    };
  }]);

Or how do you define testable directive specific functions that I don't want to expose outside of the directive?

How do I unit test a function that is defined inside a directive like the following myFunc?

angular.module('myApp')
  .directive('myDir', [function () {

    var myFunc = function (arg) {
      // code in here.
    };

    return {
      restrict: 'A',
      scope: { },
      link: function (scope, element) {

      }
    };
  }]);

Or how do you define testable directive specific functions that I don't want to expose outside of the directive?

Share Improve this question asked Jan 10, 2014 at 8:29 mkhatibmkhatib 5,2682 gold badges29 silver badges36 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

The most mon approach is to not test private methods, but instead test the public interfaces that expose their behaviour. This means that your unit test bees a contract for your public interface.

You've stated that you don't want to expose outside of the directive but of course the other option is to extract this logic into some service myDirService and perform your logic there. In that case you'll be able to test in isolation.

As pointed out by @eddiec, ideally we shouldn't be in a situation where we need to test private methods, but we don't live in an ideal world.

The way I've found that works is by putting all private vars inside a private object - say model and then have a getter function to access any of it's properties. The scope is accessible from any jasmine test once you pile the directive.

angular.module('myApp').directive('myDir', [function() {

return {
    restrict: 'A',
    scope: {

    },
    link: function(scope, element) {
        var model = {
            myPrivateVar: 'myValue'
        };

        model.myPrivateFunction = function(arg) {
            // work with arg
        };

        scope.getVal = function(prop, args) {
            // Getter function to access any private variables
            if (model.hasOwnProperty(prop)) {
                // If the requested var exists, return it.
                return args ? model[prop](args) : model[prop];
            }
            return null;
        };

    }
};
}]);

I'm still not super happy with this solution, but it works for now.

发布评论

评论列表(0)

  1. 暂无评论