Nicolas S.Xu Nicolas S.Xu - 1 month ago 13
AngularJS Question

jasmine angularjs testing - Argument 'PhoneListCtrl' is not a function, got undefined

When running an angularjs + Jasmine + Karma test, I got following error:
enter image description here

My test script is:

describe('PhoneCat controllers', function() {

describe('PhoneListCtrl', function(){

it('should create "phones" model with 3 phones', inject(function($controller) {
var scope = {},
ctrl = $controller('PhoneListCtrl', { $scope: scope });

expect(scope.phones.length).toBe(3);
}));
});
});


This code is just a copy from official AngularJS tutorial here:
http://code.angularjs.org/1.2.0-rc.3/docs/tutorial/step_02

Here is part of my karma.conf.js file:

// list of files / patterns to load in the browser
files: [

'js/bower_components/angular/angular.js',
'js/bower_components/angular/ngular-mocks.js',
'js/app/controllers.js',
'test/unit/*.js'
],


The error is PhoneListCtrl not define, but I beleive it is defined and loaded in the above code. What do you think is the problem? Thanks!

Answer

Module initialization part is missing in your unit test. You should call module('phonecatApp') before you first time call inject(). Your unit test code in this case should look like:

describe('PhoneCat controllers', function() {

  describe('PhoneListCtrl', function(){

    beforeEach(function() {
      module('phonecatApp'); // <= initialize module that should be tested
    });

    it('should create "phones" model with 3 phones', inject(function($controller) {
      var scope = {},
          ctrl = $controller('PhoneListCtrl', { $scope: scope });

      expect(scope.phones.length).toBe(3);
    }));
  });
});

where phonecatApp is the name of the module where you defined your PhoneListCtrl controller.

Also tutorial you are using is outdated, it is for unstable version of Angular (1.2.0-rc.3). Here is an updated version of the same tutorial for the latest version of Angular: http://docs.angularjs.org/tutorial/step_02