如何在Jasmine测试中注入控制器依赖?

mal*_*uri 3 jasmine angularjs

有以下控制器定义:

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

我想测试这个控制器:

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);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

"Point"是我的自定义服务,"$ modal"是Angular Bootstrap模块.我怎样才能在测试中注入它?提前致谢!

Lee*_*Lee 7

应自动注入服务.如果你想嘲笑他们或监视他们,请像这样注入:

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);
    });
  });
});
Run Code Online (Sandbox Code Playgroud)