jasmine angularjs testing - 参数'PhoneListCtrl'不是函数,未定义

时间:2014-04-13 17:10:45

标签: angularjs jasmine karma-runner

运行angularjs + Jasmine + Karma测试时,出现以下错误: enter image description here

我的测试脚本是:

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

此代码只是官方AngularJS教程的副本: http://code.angularjs.org/1.2.0-rc.3/docs/tutorial/step_02

这是我的karma.conf.js文件的一部分:

// 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'
],

错误是 PhoneListCtrl 没有定义,但我相信它是在上面的代码中定义和加载的。您认为这个问题是什么?谢谢!

2 个答案:

答案 0 :(得分:13)

单元测试中缺少模块初始化部分。您应该在第一次致电module('phonecatApp')之前致电inject()。在这种情况下,您的单元测试代码应如下所示:

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

其中phonecatApp是您定义PhoneListCtrl控制器的模块的名称。

您正在使用的教程已过时,它适用于Angular的不稳定版本(1.2.0-rc.3)。以下是Angular最新版本的同一教程的更新版本:http://docs.angularjs.org/tutorial/step_02

答案 1 :(得分:1)

这对我有用

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