Last Updated: September 27, 2021
·
2.888K
· cybersamx

Injecting Custom Controllers in an AngularJS Unit Test

Problem

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

Solution

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

describe('myNameSpace.controllers', function() {
  describe('MyController', function() {
    var scope, createController;

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

    beforeEach(inject(function($injector) {
      var $rootScope = $injector.get('$rootScope');
      scope = $rootScope.$new();

      var $controller = $injector.get('$controller');

      createController = function() {
        return $controller('MyController', {
          '$scope': scope
        });
      };
    }));

    it('should be defined', function() {
      var controller = createController();
      expect(controller).toBeTruthy();
    });
  });
});
describe('myNameSpace.controllers', function() {
  describe('MyController', function() {
    var scope, createController;

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

    beforeEach(inject(function($controller) {
      scope = {};

      createController = function() {
        return $controller('MyController', {
          '$scope': scope
        });
      };
    }));

    it('should be defined', function() {
      var controller = createController();
      expect(controller).toBeTruthy();      
    });
  });
});

A shorter version...

describe('myNameSpace.controllers', function() {
  describe('MyController', function() {
    beforeEach(module('myNameSpace.controllers'));

    it('should be defined', inject(function($controller) {
      var scope = {};

      var controller = $controller('MyController', {
        '$scope': scope
      });
      expect(controller).toBeTruthy();
    }));
  });
});