如何测试用module().controller创建的angularjs控制器?

How can I test angularjs controllers that have been created with module().controller?

本文关键字:创建 控制器 controller angularjs 何测试 测试 module      更新时间:2023-09-26

对于这个问题,我有一个angular JS控制器定义如下:

function TestController($scope) {
  $scope.name = 'eric';
}

使用我的正常node/karma/jasmine设置(在phantom, chrome, canary, firefox和safari中测试)可以正常测试:

describe('TestSquaredController', function(){
  beforeEach(inject(function(_$httpBackend_, $rootScope, $controller) {
    scope = $rootScope.$new();
    ctrl = $controller('TestController', {$scope: scope});
  }));
  it('should be called eric', function() {
    expect(scope.name).toEqual('eric');
  });
});

然而,当我使用angular模块时。控制器注册控制器的方式,我得到一个错误Error: Argument 'TestController' is not a function, got undefined时使用相同的测试。

app.module('testAngularApp')
  .controller('TestController', function($scope) {
    $scope.test = 'eric';
  });

我似乎找不到任何与此相关的东西!还有什么我应该初始化/做在我的测试?

用同样的方法测试它们。确保你在测试中通过ngMock模块中的模块函数加载了带有控制器的模块。像这样:

beforeEach(module('testAngularApp'));

我有同样的问题,在运行我们的Jasmine规范时得到相同的错误。

首先,我们尝试改变包含的顺序,就像上面的答案一样,但这并没有解决这个问题。

然后我们发现我们在应用程序的多个地方初始化了我们的模块,使用了初始化器
var app = angular.module('testAngularApp', [])

放在所有控制器js文件的顶部,而我们只需要初始化它一次,然后用

将它包含在控制器js文件的顶部
var app = angular.module('testAngularApp)

也许你也做过类似的事情?或者在第一种情况下没有正确初始化它?只是一个想法,以防你没能解决你的问题。