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

Nic*_*.Xu 8 jasmine angularjs karma-runner

运行angularjs + Jasmine + Karma测试时,出现以下错误: 在此输入图像描述

我的测试脚本是:

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);
    }));
  });
});
Run Code Online (Sandbox Code Playgroud)

这段代码只是官方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'
],
Run Code Online (Sandbox Code Playgroud)

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

Vad*_*dim 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);
    }));
  });
});
Run Code Online (Sandbox Code Playgroud)

这里phonecatApp是你定义你的模块的名称PhoneListCtrl控制器.

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