1

I'm writing Karma unit tests for angularJS using ng-describe (which I must say, is awesome).

I've got two directives. I want to test directive testing which requires somethingController.

code:

angular.module('A', [])
.directive('testing', function($compile){
  return {
    restrict: 'E',
    template: '<div>THIS TEST</div>',
    replace:true,
    controllerAs: 'testA',
    bindToController: true,
    require: '^something',
    link: function(){
      console.log('this is controller');
    }
  };
})
.directive('something', function(){
  return {
    restrict: 'E',
    template: '<div id="div1">THIS IS PARENT</div>',
    replace:true,
    controllerAs: 'sth',
    bindToController: true,
    controller: function($scope,$compile){
      console.log('this is something');
      angular.element(document.getElementById('div1'))
      .prepend($compile('<div>THIS IS compile</div>')($scope));
    }
  };
});

I'm able to run these tests successfully if I use a manual compile.

ngDescribe({
  name:'a',
  modules: 'A',
  inject:['$compile'],
  exposeApi:true,
  only:true,
  tests: function(deps, describeApi){
    it('asdfasdf', function(){
      var mockModalCtrl = {};
      deps.element = angular.element('<testing></testing>');
      deps.element.data('$somethingController', mockModalCtrl);
      inject(function($compile, $rootScope){
        $compile(deps.element)($rootScope.$new());
      });
      deps.step();
    });
  }
});

If I don't do a manual compile, I end up with an error as:

Error: [$compile:ctreq] Controller 'something', required by directive 'testing', can't be found

What I'm really trying to do:

I'm trying to use ng-describe to the fullest and get rid of the manual compile. I've tried using describeApi.setupControllers from https://github.com/kensho/ng-describe#secondary-options but I've had no luck.

  • Using a describeApi.setupElement('<testing></testing>') leaves me with the $compile error shown above.
  • Using describeApi.setupControllers('something') leaves me with the error: Error: [ng:areq] Argument 'something' is not a function, got undefined
  • I have tried to setup controllers named something, somethingController, $something, $somethingController but I've seen the undefined, not a function error there as well.

Is there a way I can make this work? I'm unable to find a solution online so far...

Jon Hanna
  • 110,372
  • 10
  • 146
  • 251
imbecile
  • 468
  • 4
  • 23

1 Answers1

3

Okay. Apparently typing out a question on SO makes your brain think twice as much as it normally does. I've figured out the solution:

var mockModalCtrl = {};
deps.element = angular.element('<testing></testing>');
deps.element.data('$somethingController', mockModalCtrl);
describeApi.setupElement(deps.element);
imbecile
  • 468
  • 4
  • 23