jasmine angularjs testing - 参数'PhoneListCtrl'不是函数,未定义 [英] jasmine angularjs testing - Argument 'PhoneListCtrl' is not a function, got undefined

查看:128
本文介绍了jasmine angularjs testing - 参数'PhoneListCtrl'不是函数,未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当运行angularjs + Jasmine + Karma测试时,我收到以下错误:

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

我的测试脚本是:

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

This code is just a copy from official AngularJS tutorial here: http://code.angularjs.org/1.2.0-rc.3/docs/tutorial/step_02

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

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

错误 PhoneListCtrl 未定义,但我相信它已定义并加载上面的代码。你觉得这个问题是什么?谢谢!

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!

推荐答案

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

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

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

where phonecatApp is the name of the module where you defined your PhoneListCtrl controller.

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

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

这篇关于jasmine angularjs testing - 参数'PhoneListCtrl'不是函数,未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆