l4fvmq
Last Updated: May 16, 2017
·
11.52K
· cybersamx
Portrait sam

Injecting Custom Services in an AngularJS Unit Test

Problem

You need to inject a custom AngularJS service object to a (Jasmine) unit test spec for testing.

Solution

There are so many ways you can inject a custom service object to a unit test spec in AngularJS. The following sample code illustrates 2 ways to inject the same custom service object to a unit test case.

describe('myNameSpace.services', function() {
  describe('MyService', function() {
    var createService;

    beforeEach(inject(function() {      
      var $injector = angular.injector(['myNameSpace.services'])

      createService = function() {
        return $injector.get('MyService');        
      }
    }));

    it('should be defined', function() {
      var service = createService();
      expect(service).toBeTruthy();
    });
  });
});
describe('myNameSpace.services', function() {
  describe('MyService', function() {
    var createService;

    beforeEach(module('myNameSpace.services'));

    beforeEach(inject(function($injector) {
      createService = function() {
        return $injector.get('MyService');        
      }
    }));

    it('should be defined', function() {
      var service = createService();
      expect(service).toBeTruthy();
    });
  });
});
Say Thanks
Respond

2 Responses
Add your response

28928

please mention the imports which are required ...as i tried injecting a service in a unit test of a pipe object creation, although your code works but I am unable to figure out the imports you have used.

7 months ago ·
28929

Here's my code -
describe('InstrumentPipe', () => {
describe('InstrumentService', function () {
var createService;
// shows compiler error on "inject(function"
beforeEach(inject(function () {
var $injector = angular.injector(['../services/InstrumentService'])
// shows compiler error on "angular.injector"

  createService = function () {
    return $injector.get('InstrumentService');
  }
}));

it('create an instance', () => {
  const pipe = new InstrumentPipe(createService);
  expect(pipe).toBeTruthy();
});

});

7 months ago ·