Last Updated: September 27, 2021
·
3.401K
· 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();
    }));
  });
});

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