ericso
ericso

Reputation: 3318

Angular Directives Tests fail after wrapping in an IIFE

After reading John Papa's AngularJS style guide on IIFEs, I began to wrap all my files in IIFEs. I ran into a problem when I wrap my menubar directive file in an IIFE. The tests fail claiming my menubar directive's controller is undefined.

ReferenceError: MenubarController is not defined at Object. (/Users/eso/dev/Prismo/frontend/prismo-frontend/app/menubar/directives_test.js:9:2473) at Object.invoke (/Users/eso/dev/Prismo/frontend/prismo-frontend/app/bower_components/angular/angular.js:9:139719) at Object.workFn (/Users/eso/dev/Prismo/frontend/prismo-frontend/app/bower_components/angular-mocks/angular-mocks.js:9:69713) TypeError: Cannot read property 'loadCurrentUser' of undefined at Object. (/Users/eso/dev/Prismo/frontend/prismo-frontend/app/menubar/directives_test.js:9:3634) Error: Unflushed requests: 1 at Function.$httpBackend.verifyNoOutstandingRequest (/Users/eso/dev/Prismo/frontend/prismo-frontend/app/bower_components/angular-mocks/angular-mocks.js:9:45282) at Object. (/Users/eso/dev/Prismo/frontend/prismo-frontend/app/menubar/directives_test.js:9:2853)

My code is too long to post here; I've provided a link to the github repo commit:

Menubar directives.js file

The tests pass before the IIFE, but fail after adding the IIFE. The other tests, however, pass; all the other controllers, services, etc, even after adding the IIFEs. Any thoughts?

Edit: Note that building the app and deploying it results in a working app with no errors. The menubar directive renders and works as expected.

Upvotes: 1

Views: 87

Answers (1)

Raulucco
Raulucco

Reputation: 3426

Because the directive is wrapped on iife you have no access to the MenubarController object on the test. Use a string instead:

ctrl = controller('MenubarController', deps, data);

On the directive file you must register the controller in your angular module with the same name and add it to the directive by string too:

.directive('menubar', function() {
    return {
      templateUrl: 'menubar/menubar.html',
      restrict: 'E',
      scope: {},
      bindToController: {
        appname: '=',
        tabs: '='
      },
      controller: 'MenubarController',
      controllerAs: 'vm'
    };
  })
  .controller('MenubarController', MenubarController)

Upvotes: 1

Related Questions