Skip to main content

AngularJS Add $scope to Controller Unit Test

First off, you really shouldn’t be adding $scope to your controller. Always use ControllerAs syntax as a best practice. If you aren’t familiar, John Papa has an excellent style guide for AngularJS coding practices: Angular 1 Style Guide

Alright, now that we got that out of the way. You probably have an edge case or something where you need to add it. Cool, I got you covered.

See the example below for how to inject $scope into your controller test case:


/* jshint -W117, -W130 */
(function() {
  'use strict';

  describe('HomeController', function() {
    beforeEach(module('app'));

    var $controller;
    var scope;

    beforeEach(inject(function(_$controller_, _$rootScope_) {
      $controller = _$controller_;
      scope = _$rootScope_.$new();
    }));

    describe('Home Controller', function() {
      var controller;

      beforeEach(function() {
        controller = $controller('HomeController', { $scope: scope });
      });

      it('should be defined', function() {
        expect(controller).toBeDefined();
      });

      it('should have a title of home', function() {
        expect(controller.title).toEqual('Home');
      });

    });
  });

})();

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *