Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 630
Nicolas S.Xu Avatar asked Apr 13 '14 17:04

Nicolas S.Xu


2 Answers

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

like image 93
Vadim Avatar answered Sep 22 '22 22:09

Vadim


this works for me

describe('addCatControllerTest', function() {

    describe('addCatController', function(){

        beforeEach(function() {
            module('app');
        });

        beforeEach(inject(function($controller, $rootScope){
            $scope = $rootScope.$new();
        }));

        it('Add Cat Controller test', inject(function($controller) {
            var scope = {},
                ctrl = $controller('addCatController', { $scope: scope });
            expect(scope.title).toBe('Add Cat');
        }));
    });
});
like image 26
misha-from-lviv Avatar answered Sep 24 '22 22:09

misha-from-lviv