Last Updated: December 31, 2020
·
19.47K
· 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 ·

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside