Include dependencies in Karma test file for Angular app?

Richard picture Richard · Nov 21, 2013 · Viewed 45.4k times · Source

I am trying to get started with Karma tests, adding them to an existing Angular app.

This is my main app definition file:

angular
  .module('myApp', [
    'ngRoute',
    'moduleAdherence'
  ]);

This is my controller file:

   angular
    .module('moduleAdherence', [])
    .controller('AdherenceCtrl', ['$scope', function ($scope) {
      $scope.awesomeThings = [1,2,3,4];
    }]);

This is my first stab at a file:

describe('Controller: AdherenceCtrl', function () {
  beforeEach(module('myApp'));
  var MainCtrl,
    scope;
  beforeEach(inject(function ($controller, $rootScope) {
    scope = $rootScope.$new();
    MainCtrl = $controller('AdherenceCtrl', {
      $scope: scope
    });
  }));
  it('should attach a list of awesomeThings to the scope', function () {
    expect(scope.awesomeThings.length).toBe(4);
  });
});

When I try to run this with grunt test, it fails with the following error:

Uncaught Error: [$injector:nomod] Module 'd3' is not available! 
You either misspelled the module name or forgot to load it. 
If registering a module ensure that you specify the dependencies 
as the second argument.
http://errors.angularjs.org/1.2.0/$injector/nomod?p0=d3
at /Users/me/Dropbox/projects/myapp/app/bower_components/angular/angular.js:1498

I don't understand this, because this controller does not Use D3. I do use D3 elsewhere in the app, in a directive, but I'm not registering it with the module (I use the external D3 file).

Why is Karma noticing D3? Shouldn't it be able to test this controller without D3?

Answer

Branislav Djuric picture Branislav Djuric · Jan 29, 2014

In karma configuration file (karma.conf.js) you need to define all libraries.

etc.

    // list of files / patterns to load in the browser
    files: [
        'app/lib/angular/angular.js',
        'app/lib/angular-route/angular-route.js',
        'test/lib/angular-mocks.js',
        'app/app.js',
        'app/controllers/*.js',
        'app/services/*.js',
        'app/*',
        'test/spec/**/*.js'
    ],