【问题标题】:Angular testing [$injector:unpr] Unknown provider: STARTUP_CONFIG角度测试 [$injector:unpr] 未知提供者:STARTUP_CONFIG
【发布时间】:2014-12-06 13:21:51
【问题描述】:

由于未正确注入依赖项,我无法运行测试。

标题中定义了我遇到的错误。我已经从我的解决方案中包含了实际的测试代码、app.js 和 index.html 文件。

问题在于我不熟悉的延迟引导程序,因为我的一位同事包含它。如果我从 app.js 文件中删除“app.config(function (STARTUP_CONFIG...”),那么测试运行良好

如何在我的测试中正确注入 STARTUP_CONFIG?

测试代码

..
..
describe("test description...", function () {

var app;
var mockupDataFactory;

beforeEach(module('Konstrukt'));

beforeEach(inject(function (STARTUP_CONFIG,BUDGETS,APPLICATIONS) {
    //failed attempt to inject STARTUP_CONFIG
}));

beforeEach(function () {
    app = angular.module("Konstrukt");
});

beforeEach(function () {
    mockupDataFactory = konstruktMockupData.getInstance();
});

it('should be accessible in app module', function () {
    expect(app.pivotTableService).toNotBe(null); //this test runs fine
});

it('test decr...', inject(function ( pivotTableService) {
    ... //Fails here
..
..

app.js

  ..
    ..        
    angular.module('Konstrukt', ['ngGrid', 'ngSanitize', 'ngRoute','pasvaz.bindonce', 'ngAnimate', 'nvd3ChartDirectives', 'ui.select', 'ngProgress', 'ui.grid', 'ui.grid.edit','ui.grid.selection', 'ui.grid.cellNav', 'ui.grid.pinning', 'ui.grid.resizeColumns']);

          var app = angular.module('Konstrukt');
          app.config(function (STARTUP_CONFIG, BUDGETS, APPLICATIONS) {

        var STARTUP_CONFIG = STARTUP_CONFIG;
        var BUDGETS = BUDGETS;
        var APPLICATIONS = APPLICATIONS;

      });
      ..
      ..

index.html

    ..
    ..

    <script>
  setTimeout(function(){
  window.deferredBootstrapper.bootstrap({
    element: window.document.body,
    module: 'Konstrukt',
    resolve: {
      STARTUP_CONFIG: ['$http', function ($http) {
        return $http.get('/scripts/_JSON/activeBudgets.JSON');
      }],
      BUDGETS: ['$http', function ($http) {
        return $http.get('/scripts/_JSON/activeBudgets.JSON');
      }],
      APPLICATIONS: ['$http', function ($http) {
        return $http.get('/scripts/_JSON/applications.JSON');
      }]
    }
  })
  } , 1500);
</script>

【问题讨论】:

    标签: angularjs unit-testing jasmine


    【解决方案1】:

    deferredBootstrapper 不会在您的单元测试中运行,这意味着它通常添加到您的模块中的常量将不可用。

    您可以添加一个全局 beforeEach 来提供它们的模拟版本:

    beforeEach(function () {
      module(function ($provide) {
        $provide.constant('STARTUP_CONFIG', { something: 'something' });
        $provide.constant('BUDGETS', { something: 'something' });
        $provide.constant('APPLICATIONS', { something: 'something' });
      });
    });
    

    【讨论】:

    • 成功了,谢谢。由于我在测试中根本没有使用(并且显然不能)这些常量,所以它开箱即用:=)
    猜你喜欢
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 2017-04-16
    • 2014-10-01
    • 2023-03-08
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    相关资源
    最近更新 更多