首页 > 解决方案 > 服务抛出未知提供者错误 - Angularjs单元测试

问题描述

我正在尝试修复很久以前设置的一些损坏的单元测试。由于某种原因,当我们运行测试时,它们都失败了,因为每次服务注入都会出现“未知的提供者错误”。我做了很多搜索,我看不出测试有任何明显的问题。如果测试没有问题,这可能是配置问题吗?我已经玩过文件加载的顺序,这似乎并不重要。

"use strict";

describe("Catalogs controller", function() {

  beforeEach(angular.mock.module("photonControllersPreSession"));



  var $rootScope;

  var $scope;
  var createController;
  var $window;
  var $location;
  var loggerService;
  var catalogService;
  var feedbackService;


  beforeEach(
    inject( function(
      $controller,
      _$rootScope_,
      _$window_,
      _$location_,
      _loggerService_,
      _catalogService_,
      _feedbackService_
    ) {
      $rootScope = _$rootScope_;
      $window = _$window_;
      $location = _$location_;
      loggerService = _loggerService_;
      catalogService = _catalogService_;
      feedbackService = _feedbackService_;
      $scope = $rootScope.$new();

      spyOn(loggerService, "info");

      createController = function() {
        return $controller("CatalogController", {
          $scope: $scope,
          $location: $location,
          $window: $window,
          loggerService: _loggerService_,
          catalogService: _catalogService_,
          feedbackService: _feedbackService_
        });
      };
    })
  );


  it("Should init", function() {
    var catalogController = null;
    catalogController = createController();
    console.log("test: " + createController);


    // Just want to see if the controller is created.
    expect(catalogController).not.toBe(null);
  });
});

标签: angularjsunit-testingjasminekarma-jasminekarma-runner

解决方案


AngularJS 确实要求在开始测试之前加载所有模块。您只有一个模块photonControllersPreSession包含在这个特定的测试套件中。

确保 , , CatalogController,loggerService属于catalogService模块feedbackServicephotonControllersPreSession或者它们的模块也包含在photonControllersPreSession中。

例如,如果loggerService是某个其他模块的一部分,可以说mySuperModule,请确保mySuperModule已像这样包含在内

angular.module('photonControllersPreSession', [
  'mySuperModule'  
]);

否则您必须在每次测试之前手动包含所有模块

beforeEach(() => {
  module('mySuperModule');
  module('photonControllersPreSession');
});

推荐阅读