lundi 28 décembre 2015

How to test controller in a directive?

angular.module('myModule', ['somedeps'])
  .directive('myAwesomeDirective', myAwesomeDirectiveFn)


function myAwesomeDirectiveFn() {
  function myAwesomeDirectiveCtrl (someDeps) {
    var vm = this;
    vm.variable_x, vm.variable_y;
    
    vm.action_a = function action_a() {
      console.log("Yaaa, I am action a");
    }
  },
    
  function myAwesomeLinker(scope, element, attribute, controller) {
    //Just print something on console
    element.on('click', function () {
      controller.action_a();
    });
  }
  
  return {
    restrict : 'AE',
    scope : {
      x : '=',
      y : '='
    },
    controller : myAwesomeDirectiveCtrl,
    controllerAs : 'vm',
    link : myAwesomeLinker,
    templateUrl : 'someTemplate.html'
  }
}

Now I want to write a unit test to test my directive and controller inside it.

I get the directive by doing following

directiveElement = angular.element('<my-awesome-directive x = "x" y = "y" />');
var vm = $rootScope.$new();
vm.x = 10;
vm.y = 20;

directiveElement = $compile(directiveElement)(vm);
vm.$digest();

My understanding was that I can get the controller by doing following

controller = directiveElement.controller('myAwesomeDirective');

but controlller is still undefined.

What am I doing wrong or is this completely wrong? I want to encapsulate my directive with controller. I do not want to create any controller on module.

Aucun commentaire:

Enregistrer un commentaire