How to write testable controllers with private methods in AngularJs?

前端 未结 4 1370
遇见更好的自我
遇见更好的自我 2020-12-12 14:28

Alright, so I have been stumbling upon some issue for a long time and I would like to hear an opinion from the rest of community.

First, let\'s look at some abstract

4条回答
  •  盖世英雄少女心
    2020-12-12 14:59

    Namespacing it on the scope is pollution. What you want to do is extract that logic into a separate function which is then injected into your Controller. i.e.

    function Ctrl($scope, util) {
    
       $scope.field = "field";
       $scope.whenClicked = function() {
          util();
       };
    }
    
    angular.module("foo", [])
           .service("anyService", function(...){...})
           .factory("util", function(anyService) {
                  return function() {
                         anyService.doSmth();
                  };
           });
    

    Now you can unit test with mocks your Ctrl as well as "util".

提交回复
热议问题