且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将 Jasmine 与 AngularJS 一起使用时出错

更新时间:2023-02-06 10:29:58

1) 尝试将控制器作为模块上的字段进行访问是错误的.在您的测试中,您应该将 $controller 注入到您的测试以创建您的控制器.这意味着您应该编写如下测试:

1) You are making a mistake by trying to access your controller as a field on a module. in your test you should be injecting $controller into your test to create your controller. What that means is that you should be writing your tests like the following:

it('should have a mailctrl', inject(function($rootScope, $controller) {
   var controller = $controller('mainctrl', { $scope: $rootScope.$new(), $rootScope: $rootScope, ...  }) // rest of your dependencies
   expect(controller).toBeDefined();
}));

2) 见 1

3) angular.mock.module 用于将您的模块注册到您的测试 中的注入器.它与 module 相同.angular.module 用于为您的应用程序创建、注册或检索模块.

3) angular.mock.module is used to register your module to the injector in your tests. It is the same thing as module. angular.module is used to create, register or retrieve a module for your application.

关于您的

您没有提供 routeParams 和您的控制器所依赖的任何其他服务,因此 $injector 不知道从哪里获取它们并抛出此错误.$injector 必须知道为控制器所需的每个参数注入什么.你的控制器依赖于

You are not providing routeParams and any other service that your controller depends on so $injector does not know where to get them from and is throwing this error. $injector has to know what to inject for every parameter that is required by your controller. Your controller depends on

  • $rootScope:由 angular 提供
  • $scope:可以通过$rootScope.$new()创建
  • getMailData:这是你的服务,你必须为此提供一个模拟
  • $routeParams:这是 angular 内置结构,但没有专门的 mock,但由于它是一个非常简单的对象,您可以自己为此提供一个 mock.
  • $angularCacheFactory:这是第三方服务,您也必须为此提供模拟
  • $rootScope: provided by angular
  • $scope: can be created by $rootScope.$new()
  • getMailData: This is your service, you have to provide a mock for this
  • $routeParams: This is angular built-in structure but there is not a dedicated mock, but since it is a very simple object you can provide a mock for this yourself.
  • $angularCacheFactory: this is a third party service and you have to provide a mock for this as well

所以最后你应该像这样创建你的控制器:

So in the end you should be creating your controller like this:

it('should have a mailctrl', inject(function($rootScope, $controller) {
   var controller = $controller('mainctrl', { 
         $scope: $rootScope.$new(), 
         '$routeParams': {}, // whatever  it needs to be to be able to test your controller
         $rootScope: $rootScope, 
         'getMailData': getMailDataMOCK // this object is created by you in your test code
         '$angularCacheFactory': $angularCacheFactoryMOCK
       }) 
   expect(controller).toBeDefined();
}));

如果您不提供任何这些参数,那么它会尝试从 $injector 获取它,并在找不到时抛出异常.

If you don't provide any of these arguments then it will try to get it from $injector and will throw an exception when not found.