错误:已经创建了Injector,无法注册模块

时间:2017-12-21 07:44:05

标签: angularjs jasmine

我正在尝试测试在方法结束时window.location是否设置为特定网址,但是我收到此错误:

Error: Injector already created, can not register a module!

代码:

describe('Home controller', function() {

  var $controller, $location, $window, $http, $timeout, $filter, $scope, $resource;

  beforeEach(module('app', function($provide) {
    $provide.value('$window', {
      location: {
        href: ''
      }
    });
  }));

  beforeEach(inject(function(_$controller_, _$location_, _$window_, _$rootScope_, _$http_,
    _$resource_, _$timeout_, _$filter_) {

    $controller = _$controller_;
    $location = _$location_;
    $window = _$window_;
    $http = _$http_;
    $timeout = _$timeout_;
    $filter = _$filter_;
    $scope = _$rootScope_.$new();

  }));

  it('check Home Ctrl', inject(function($rootScope, $httpBackend, API_URL) {

    var ctrlInstance = $controller('HomeCtrl', {
      $scope: $scope,
      $rootScope: $rootScope,
      $http: $http,
      $resource: $resource,
      $location: $location,
      $window: $window,
      $timeout: $timeout,
      API_URL: API_URL
    });

    $scope.goEditUser({
      userId: 2
    });
    expect($window.location.href).toContain('/switch-user/2');


  }));
});

为什么即使在模块之后调用注入时我也会收到错误?

1 个答案:

答案 0 :(得分:0)

您可以尝试使用单注入方法:

var ctrlInstance;
beforeEach(module('app');
beforeEach(module(function($provide) {...})

和类似的东西

it('check Home Ctrl', inject(function($controller, _$location_, _$window_, _$rootScope_, _$http_, _$resource_, _$timeout_, _$filter_) {

  var ctrlInstance = $controller('HomeCtrl', {
    $location : _$location_,
    $window : _$window_,
    $http : _$http_,
    $timeout : _$timeout_,
    $filter : _$filter_,
    $scope : _$rootScope_.$new(),
    $rootScope: _$rootScope_,
    $resource: _$resource_,
    API_URL: API_URL
  });

  $scope.goEditUser({
    userId: 2
  });

  expect($window.location.href).toContain('/switch-user/2');

}));