Search code examples
javascriptangularjsjasminekarma-jasmineangular-mock

Controller is undefined in jasmine test


karma.config.js:

module.exports = function(config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine'],
    files: [
      'node_modules/angular/angular.min.js',
      'node_modules/angular-mocks/angular-mocks.js',
      'node_modules/angular-translate/dist/angular-translate.min.js',
      'browser/javascripts/*.js',
      'browser/tests/*.spec.js'
    ],
    exclude: [],
    preprocessors: {},
    reporters: ['progress'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['Chrome'],
    singleRun: false,
    concurrency: Infinity
  })
};

home.spec.js:

describe('Home Controller', function() {
  beforeEach(
    module('pascalprecht.translate'),
    module('tradeshiftApp')
  );
  var $controller;
  beforeEach(inject(function(_$controller_){
    $controller = _$controller_;
  }));

  it('should exist', function(){
    controller = $controller('HomeController', {
      $scope: {}
    });
    expect(controller).not.toBe(undefined);
  })
});

I am using karma-jasmine and the problem is following: my app.js file has this module and it's loading correctly:

var app = angular.module('tradeshiftApp', ['pascalprecht.translate']);

But when I try to mock my controller, which is

app.controller('HomeController', function ($scope, $req, $window, $translate, $q) { 
  // some code 
});

I get an error, which says that HomeController is not a function. As you can see, dependencies are wired up and everything should be fine, I guess. Any tips?

Note: I've tried to inject $rootScope and get $rootScope.$new() and it's successful.


Solution

  • So, the problem was in 'pascalprecht.translate' module. In my code I have a small dependency wired to the foregoing module, which was included in my HTML file, but not in my Karma config file. Guys, be careful and vigilant about your code :)