• Skip to main content
  • Skip to primary sidebar

Ryan McCormick

AngularJS Add $scope to Controller Unit Test

March 19, 2017 by Ryan Leave a Comment

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

    });
  });

})();

Filed Under: AngularJS (1x branch) Tagged With: add $scope, angularjs, jasmine, unit testing

Reader Interactions

Leave a Reply Cancel reply

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

Primary Sidebar

Recent Posts

  • Force Quit Kill all Chrome Windows MacOS
  • SOLVED: Angular 6 CLI Karma Stuck in Single Run | Karma Stops Running
  • How to Manually Install Java 8 on Ubuntu 18.04 LTS
  • Remove VirtualBox from Ubuntu 16.04 Xenial
  • Clear all Node Modules Folders Recursively Mac/Linux

Recent Comments

  1. KKV on Webstorm adding spaces between imports and braces | JavaScript and TypeScript
  2. jusopi on Clear all Node Modules Folders Recursively Mac/Linux
  3. Qaisar Irfan on Clear all Node Modules Folders Recursively Mac/Linux
  4. mustafa on Remove VirtualBox from Ubuntu 16.04 Xenial
  5. Pourya on How to Manually Install Java 8 on Ubuntu 18.04 LTS

Copyright © 2025 · Magazine Pro on Genesis Framework · WordPress · Log in