简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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