5

我刚刚安装了 Yeoman 并创建了我的第一个项目。我正在尝试对 Yo 创建的默认 Angular 项目进行单元测试。当我调用“grunt server”时,项目运行良好,但是当我运行单元测试“grunt test:unit”时,我收到错误“Argument 'MainCtrl' 不是函数,未定义”。

为了让这个测试正常运行,我缺少什么?

再次感谢

- 控制器

'use strict';

angular.module('myApp')
.controller('MainCtrl', function ($scope) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma',
'mytest'
  ];
});

-- unti 测试

 'use strict';

 describe('Controller: MainCtrl', function () {

 // load the controller's module
 beforeEach(module('myApp'));

var MainCtrl,
 scope;

  // Initialize the controller and a mock scope
 beforeEach(inject(function ($controller, $rootScope) {
  scope = $rootScope.$new();
 MainCtrl = $controller('MainCtrl', {
 $scope: scope
});
}));

it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings.length).toBe(4);
});
});
4

2 回答 2

3

如果我复制并粘贴此代码,它将毫无问题地执行。您收到的错误消息表明喷油器不知道控制器(名称)。您是否忘记在karma.conf.js中包含控制器 javascript 文件?

于 2013-10-26T06:18:31.583 回答
0

就我而言,它是“app.js”的副本,它导致了同样的错误。虽然它没有在任何地方的 html 页面中使用,但由于 grunt 测试包含 /**/* 模式,它被包含在内,因此重复了模块的定义,可能会重置从app.js. 所以我收到了如下错误:

Error: [ng:areq] Argument 'MainCtrl' is not a function, got undefined http://errors.angularjs.org/1.4.7/ng/areqp0=MainCtrl&p1=not%20a%20function%2C%20got%20undefined

删除此文件后,一切正常。我花了很长时间才弄清楚出了什么问题,但终于找到了原因。

于 2015-11-04T05:55:27.683 回答