简体   繁体   English

将服务注入角度控制器单元测试

[英]Injecting a service into angular controller unit test

I'm trying to inject a service into my controllers unit test. 我正在尝试将服务注入到我的控制器单元测试中。 I'm not looking to make a mock out of the service but just include it so that I can have access to all of its methods. 我并不是想对服务进行模拟,而只是将其包括在内,以便我可以访问其所有方法。 Is this possible? 这可能吗?

'use strict';

  describe('Offers : controller', function(){

    beforeEach(module('client'));

      var $scope,
          controller,
          $rootScope,
          genericService;


      beforeEach(inject(function($injector, $controller) {

        $rootScope = $injector.get('$rootScope');
        controller = $controller('OffersCtrl', { $scope: $scope });
        genericService = $injector.get('genericService');
        $scope = $rootScope.$new();

   }));

   it('should have a genericService', function () {
     expect(genericService.method).toBeDefined();
   });


});

Just inject your own service the same way you did with the angular services: 只需以与角度服务相同的方式注入自己的服务即可:

var genericService;

beforeEach(inject(function(_genericService_) {
  genericService = _genericService_;
});

Note that you can use underscores around the argument name to avoid naming conflicts. 请注意,您可以在参数名称周围使用下划线 ,以避免命名冲突。 Angular will strip those from the argument name when resolving the services to inject. 解决注入服务时,Angular将从参数名称中删除这些参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM