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

2024-02-18

有以下控制器定义:

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

我想测试这个控制器:

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”是我的自定义服务,“$modal”是 Angular Bootstrap 模块。我如何将它注入到我的测试中?提前致谢!


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

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);
    });
  });
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Jasmine 测试中注入控制器依赖项? 的相关文章

随机推荐