Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject controller dependencies in Jasmine tests?

There is the following controller definition:

angular.module('app.controllers', []).controller('HomeController', [
  '$scope', '$modal', 'Point', function($scope, $modal, Point) { //some action }

I want to test this controller:

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

  var $controller;

  beforeEach(inject(function(_$controller_){
    // The injector unwraps the underscores (_) from around the parameter names when matching
    $controller = _$controller_;
  }));

  describe('$scope.grade', function() {
    it('sets the strength to "strong" if the password length is >8 chars', function() {
      var $scope = {};
      var controller = $controller('HomeController', { $scope: $scope });
      $scope.label = '12345';
      $scope.addNewPoint();
      expect($scope.label).toEqual(null);
    });
  });
});

"Point" is my custom service, "$modal" is Angular Bootstrap module. How can I inject it in my tests? Thanks in advance!

like image 425
malcoauri Avatar asked Feb 01 '26 01:02

malcoauri


1 Answers

The services should be automatically injected. If you wish to mock them or spy on them, inject them like so:

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

  var $controller, $scope, $modal, Point;

  beforeEach(inject(function(_$controller_, _$rootScope_, _$modal_, _Point_){
    $scope = $rootScope.$new();
    $modal = _$modal_;
    Point = _Point_;

    spyOn($modal, 'method');
    spyOn(Point, 'method');

    $controller = _$controller_('HomeController', { $scope: $scope, $modal: $modal, Point: Point });
  }));

  describe('$scope.grade', function() {
    it('sets the strength to "strong" if the password length is >8 chars', function() {
      $scope.label = '12345';
      $scope.addNewPoint();
      expect($scope.label).toEqual(null);
    });
  });
});
like image 67
Lee Avatar answered Feb 02 '26 14:02

Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!