How to inject controller dependencies in Jasmine tests?

拟墨画扇 提交于 2019-12-22 09:57:34

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/32602238/how-to-inject-controller-dependencies-in-jasmine-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!