jasmine angularjs 测试 - 参数“PhoneListCtrl”不是函数,未定义

2024-03-05

When running an angularjs + Jasmine + Karma test, I got following error: 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 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'
],

错误是电话列表控件没有定义,但我相信它是在上面的代码中定义和加载的。您认为问题出在哪里?谢谢!


您的单元测试中缺少模块初始化部分。你应该打电话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);
    }));
  });
});

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

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

jasmine angularjs 测试 - 参数“PhoneListCtrl”不是函数,未定义 的相关文章

随机推荐