Last Updated: December 31, 2020
·
18.88K
· cybersamx

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

3 Responses
Add your response

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.

over 1 year ago ·

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

});

over 1 year ago ·
const module = angular.mock.module;
const inject = angular.mock.inject;
let searchService;

  describe('Testing some awesome service', () => {
    beforeAll(module('yourModule'));

   beforeEach(inject($injector => {
     searchService = $injector.get('SearchClass');
   }));

  it('Should be defined', () => {
    expect(searchService).toBeDefined();
  });
)}
over 1 year ago ·