Search code examples
angularjsunit-testingkarma-runnerkarma-mocha

Karma: ReferenceError: app is not defined


I followed the tutorial from http://www.yearofmoo.com/2013/01/full-spectrum-testing-with-angularjs-and-karma.html for testing AngularJS apps with Karma.

My karma.conf.js looks like this:

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: [
      'public/bower_components/angular/angular.min.js',
      'public/bower_components/angular-route/angular-route.min.js',
      'public/bower_components/d3/d3.js',
      'public/bower_components/nvd3/nv.d3.js',
      'public/bower_components/angularjs-nvd3-directives/dist/angularjs-nvd3-directives.js',
      'public/bower_components/angular-mocks/angular-mocks.js',
      'public/scripts/**/*.js',
      'test/*Spec.js'
    ],
    exclude: [
    ],
    preprocessors: {
    },
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false
  });
};

And my test:

describe("app", function() {

  beforeEach(angular.mock.module('app'));

  it('should have a HomeController', function() {
    expect(app.HomeController).not.to.equal(null);
  });

});

public/scripts/app.js

angular.module('app', [
  'ngRoute',
  'app.controllers',
  'nvd3ChartDirectives'
]);

I get an output in the console saying: app should have a HomeController FAILED ReferenceError: app is not defined

Any help would be appreciated,

Thanks in advance!


Solution

  • Solved with:

    describe('app', function(){
      beforeEach(module('app'));
    
      var ctrl, scope;
      beforeEach(inject(function($controller, $rootScope) {
        scope = $rootScope.$new();
        ctrl = $controller('HomeController', {
          $scope: scope
        });
      }));
    
      it('should have defined HomeController', function() {
        expect(ctrl).toBeDefined();
      });
    }