Testing angular directive controllers

Testing angular directive controllers using controllerAs and Jasmine

by morloch

HTML

<script src="http://jasmine.github.io/1.3/lib/jasmine.js"></script>
<script src="http://jasmine.github.io/1.3/lib/jasmine-html.js"></script>
<link rel="stylesheet" href="http://jasmine.github.io/1.3/lib/jasmine.css">
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.angularjs.org/1.3.20/angular.js"></script>
<script src="http://code.angularjs.org/1.3.20/angular-mocks.js"></script>

JavaScript

//--- CODE --------------------------
angular.module('testApp', [])
  .directive('myDirective', function() {
    var targetElement;
    function MyController() {
      var vm = this;
      vm.onSelection = function() {
        targetElement.val('calculated stuff');
        targetElement.trigger('input');
      }
    }
    return {
      template: '<div></div>',
      restrict: 'A',
      scope: {},
      link: function postLink(scope, element, attrs) {
        targetElement = element;
      },
      controller: MyController,
      controllerAs: 'vm',
      bindToController: true
    };
  });

//--- SPECS -------------------------
describe('Directive: myDirective', function() {
  // load the directive's module
  beforeEach(module('testApp'));

  var element, controller, scope;

  beforeEach(inject(function($rootScope, $compile) {
    scope = $rootScope.$new();
    element = angular.element('<input my-directive type="text" id="bar">');
    $compile(element)(scope);
    scope.$digest();
    controller = element.controller('myDirective');
  }));

  it('should have an empty val', inject(function() {
    expect(element.val()).toBe('');
  }));

  it('should have a calculated val after select', inject(function() {
    controller.onSelection();
    expect(element.val()).toBe('calculated stuff');
  }));
});

// --- Runner -------------------------
(function() {
  var jasmineEnv = jasmine.getEnv();
  jasmineEnv.updateInterval = 1000;

  var htmlReporter = new jasmine.HtmlReporter();

  jasmineEnv.addReporter(htmlReporter);

  jasmineEnv.specFilter = function(spec) {
    return htmlReporter.specFilter(spec);
  };

  var currentWindowOnload = window.onload;

  window.onload = function() {
    if (currentWindowOnload) {
      currentWindowOnload();
    }
    execJasmine();
  };

  function execJasmine() {
    jasmineEnv.execute();
  }

})();