Skip to content

Instantly share code, notes, and snippets.

@coreypnorris
Last active January 12, 2017 11:36
Show Gist options
  • Select an option

  • Save coreypnorris/316a2499b0fb97f2a4773edf99a294c1 to your computer and use it in GitHub Desktop.

Select an option

Save coreypnorris/316a2499b0fb97f2a4773edf99a294c1 to your computer and use it in GitHub Desktop.
Inject a service into controller test

Given a controller that uses the $location service

'use strict';

/**
 * @ngdoc function
 * @name categoryManagerApp.controller:CategoryCtrl
 * @description
 * # CategoryCtrl
 * Controller of the categoryManagerApp
 */
angular.module('categoryManagerApp')
  .controller('CategoryCtrl', ['$scope', '$location', function ($scope, $location) {
    $scope.go = function ( path ) {
      $location.path( path );
    };
  }]);

Inject the service in 3 steps

'use strict';

describe('Controller: CategoryCtrl', function () {

  // load the controller's module
  beforeEach(module('categoryManagerApp'));

  var CategoryCtrl,
    scope,
    $location; // <-- Step 1 Instantiate the variable.

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope, _$location_) {
    scope = $rootScope.$new();
    $location = _$location_; // <-- Step 2 Inject the service and set it to the variable.
    CategoryCtrl = $controller('CategoryCtrl', {
      $scope: scope,
      $location: $location // <-- Step 3 Set it in the mocked controller.
      // place here mocked dependencies
    });
  }));

  it('should attach a function called go to the scope', function () {
    var go = function ( path ) {
      $location.path( path );
    };
    expect(scope.go).toBeDefined();
    expect($location).toBeDefined();
    expect(typeof(scope.go)).toBe('function');
    expect(scope.go.toString() == go.toString()).toBe(true);
  });
});
  1. Instantiate the $location variable.
  2. Inject the _$location_ service and set it to the variable.
  3. Set it in the mocked controller.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment