7

I am having a few problems accessing my controller on a directive that I am trying to unit test with jasmine and karma testrunner. The directive looks like this:

directive

angular.module('Common.accountSearch',['ngRoute'])

    .directive('accountSearch', [function() {
        return {
            controllerAs: 'ctrl',
            controller: function ($scope, $element, $routeParams, $http) {

                this.setAccount = function () {
                    var response = { AccountId : $scope.ctrl.searchedAccount.AccountId }
                    $scope.callback(response)
                }


                this.getAccounts = function(searchText){
                    return $http.get('/api/CRMAccounts', {
                        params: {
                            retrievalLimit: 10,
                            search: searchText
                        }
                    }).then(function(response){
                        return response.data;
                    });

                }

            },
            scope : {
                config : '=',
                values : '=',
                callback : '='
            },
            templateUrl : '/common/components/account-search/account-search.html',
            restrict : 'EAC'
        }
    }]);

This here is the test case file so far I believe all is in order and correct (I hope):

test case file:

    describe("Account search directive logic tests", function (){
  var element,$scope,scope,controller,template

  beforeEach(module("Common.accountSearch"))


  beforeEach(inject( function (_$compile_, _$rootScope_,_$controller_,$templateCache) {
    template = $templateCache.get("components/account-search/account-search.html")
    $compile = _$compile_;
    $rootScope = _$rootScope_;
    $controller = _$controller_;
    scope = $rootScope.$new();
    element = $compile(template)(scope)
    ctrl = element.controller
    scope.$digest();
  //  httpBackend = _$httpBackend_;
  }));




  it(" sets the account and calls back.", inject(function () {

    console.log(ctrl)
    expect(ctrl).toBeDefined()
   }));
  //httpBackend.flush()
});

I have managed to print the controller of the directive ( I think) to the console which returns the following ambiguous message:

LOG: function (arg1, arg2) { ... }

I cannot access any of the functions or properties on the directive as they are all returning "undefined", what am I doing wrong?

5
  • You can access it like this scope.ctrl
    – Kliment
    Nov 12, 2016 at 12:08
  • I find it easier of the controller is it own file, that you could perhaps test easier without the context of a directive
    – Maccurt
    Nov 13, 2016 at 15:01
  • I have tried scope.ctrl , it was one of the fist things I did and it did not work
    – nagrom97
    Nov 14, 2016 at 9:07
  • I don't get it, what are you trying to test ? That your directive search properly ? Then you should not try to get the controller to call it, since it is not how your directive is used. You should try to parse a template using the directive and mock a user action which will trigger the directive to search as it was a user action.
    – Walfrat
    Nov 15, 2016 at 9:34
  • Just for the sake of the question, Your var definition is named as 'controller' but then you try accessing it as 'ctrl'? That would not create a local variable? It may be just a typo when you made the question though. Nov 17, 2016 at 1:23

3 Answers 3

6

Controllers for directives are actually fully injectable - instead of providing a constructor, you can just refer to the controller by name. See the directive definition object docs for Angular here: https://docs.angularjs.org/api/ng/service/$compile#directive-definition-object

In your case where you want to unit test the controller you'd just do it like this:

common.accountSearch.js

angular.module('Common.accountSearch', [])
  .directive('accountSearch', [function () {
      return {
          controller: 'accountSearchCtrl',
          scope: {
              config    : '=',
              values    : '=',
              callback  : '='
          },
          templateUrl : '/common/components/account-search/account-search.html',
          restrict: 'EAC'
      }
  }])
  .controller('accountSearchCtrl', ['$scope', function ($scope) {
      $scope.setAccount = function () {
          var response = {
              AccountId: $scope.ctrl.searchedAccount.AccountId
          };
          $scope.callback(response);
      }

      $scope.getAccounts = function (searchText) {
          // Code goes here...
      }
  }]);

common.accountSearch-spec.js

describe("Account search directive logic tests", function () {    
    var controller, scope;

    beforeEach(module("Common.accountSearch"));

    beforeEach(inject(function (_$controller_, _$rootScope_) {        
        $rootScope = _$rootScope_;
        scope = $rootScope.$new();
        controller = _$controller_('accountSearchCtrl', { '$scope': scope });        
    }));

    it(" sets the account and calls back.", function () {
        expect(controller).toBeDefined();
    });
});

This way you can just inject your controller directly into your jasmine tests like any of your other controllers.

Hope this helps.

3
  • Ive tried this and it doesnt work. Can you add an example?
    – dopatraman
    Nov 15, 2016 at 19:06
  • Hmm, guess I made a mistake somewhere. I'll throw together a working fiddle when I've got fifteen minutes, and update my answer.
    – s3raph86
    Nov 15, 2016 at 23:45
  • Alright, I've tested and updated my answer. To simplify, I removed a few of the dependencies from the controller, but you should just be able to add them back in one-by-one as you develop your mocks and specs. The above will definitely inject the accountSearchCtrl both into the spec, and into the directive, which will fullfil your requirement of unit testing your directive's controller.
    – s3raph86
    Nov 16, 2016 at 0:47
6

So close!

element.controller is a function and needs to be passed the name of the directive which you're attempting to get the controller for. In this case it would be

ctrl = element.controller("accountSearch");
1
  • Where is the doc for this function? Can you post a link?
    – GC_
    Apr 24, 2018 at 13:19
0

element.controller is an additional method to AngularJS jqLite, so when you log it you see jqLite method .toString(). You should call it and get a directive controller. Element controller manual

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.