Getting error while using Jasmine with AngularJS

孤街浪徒 提交于 2019-12-01 08:26:19
idursun

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) See 1

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.

Regarding your edit:

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!