How to mock AngularJS Directive controller

Given a directive having an external controller:

.directive('d1', function () {
  return {
    controller: 'd1controller',
    restrict: 'E',
    link: function ($scope, $element, $attributes, $controller) {

      $controller.doStuff();

    }
  };
});

How do I make fun of a controller d1controllerin test modules d1?


My attempts:

I tried with $provide, as in bullying service:

  beforeEach(module('app', function ($provide) {
    ctrlMock = jasmine.createSpyObj('ctrlMock', ['doStuff']);
    $provide.value('d1controller', ctrlMock );
  }));

And I also tried with $controllerProvider

  beforeEach(module('app', function ($controllerProvider) {
    ctrlMock = jasmine.createSpyObj('ctrlMock', ['doStuff']);
    $controllerProvider.register('d1controller', ctrlMock);
  }));
+3
source share
2 answers

I am OP. It turns out it works $controllerProvider. You must pass it a constructor; not an instance.

beforeEach(module('app', function ($controllerProvider) {
  $controllerProvider.register('d1controller', function Mock(){
    this.doStuff = function(){};
  });
}));
+3
source

I had decent luck creating a mock module containing all my mocked services / controllers and then including this module module after my application module. This will essentially override all the services / controllers that you have in your modular module.

, .

appMock = angular.module('appMock', []);

appMock.controller('ControllerToMockCtrl', ['$scope', function($scope) {
    $scope.greeting = 'Hola!';
}]);

.

beforeEach(function(){
  module('app');
  module('appMock');
});

- . http://southdesign.de/blog/mock-angular-js-modules-for-test-di.html#using-the-mock

+1

All Articles