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

别说谁变了你拦得住时间么 提交于 2019-12-08 17:09:53

问题


When running an angularjs + Jasmine + Karma test, I got following error:

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!


回答1:


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




回答2:


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');
        }));
    });
});


来源:https://stackoverflow.com/questions/23045706/jasmine-angularjs-testing-argument-phonelistctrl-is-not-a-function-got-unde

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!