【问题标题】:Testing Angular Service with Jasmine: Failed to instantiate module app使用 Jasmine 测试 Angular 服务:无法实例化模块应用程序
【发布时间】:2018-04-24 21:29:50
【问题描述】:

我正在尝试使用 Jasmine 为 Angular 服务创建一个简单的单元测试。 但是当我通过 Karma 运行测试时,我收到以下错误:

Failed to instantiate module app

而且我不知道为什么会出现此错误。我用谷歌搜索并尝试应用以下解决方案。但没有一个奏效。

  • 我尝试更改 karma.conf.js 中的文件顺序。
  • 我尝试以不同的方式编写单元测试。我的意思是以不同的方式注入服务。

但错误依旧。

这是一个非常简单的代码。请在下面找到代码以供参考:

string.service.js

(function () {
    "use strict";

    angular
        .module('app')
        .factory("stringService", stringService)

    function stringService() {

        return {
            checkForAlphaNumeric: checkForAlphaNumeric,
        };

        function checkForAlphaNumeric(string) {
            var regex = /^[a-zA-Z0-9]+$/;
            return regex.test(string);
        }
    }
})();

string.service.spec.js

describe("-----> String Service", function () {

    var stringService;
    beforeEach(function () {
        angular.mock.module('app');
        inject(function ($injector) {
            stringService = $injector.get('stringService');
        });
    });

    it("--> stringService should be Defined.", function () {
        expect(stringService).toBeDefined();
    });
});

karma.conf.js

// list of files / patterns to load in the browser
files: [
  //External
  './node_modules/angular/angular.js', // Angular Framework
  './node_modules/angular-mocks/angular-mocks.js', // Loads the Module for Tests
  './node_modules/@uirouter/angularjs/release/angular-ui-router.js', // UI-Router
  './node_modules/angular-route/angular-route.js',

  //Sub Modules
  './app/authentication/authentication.module.js',

  //Main Module
  './app/app.module.js', // Angular App

  //Controllers
  './app/authentication/login.controller.js',

  //Services and Factories
  './app/services/string.service.js',

  //Specs
  './app/licensing/licensing.controller.spec.js',
  './app/services/string.service.spec.js'
],
  • 交换模块和子模块引用也不起作用。
  • 将模块和子模块引用放在控制器和服务之前或之后也不起作用。

任何帮助将不胜感激。

【问题讨论】:

    标签: angularjs jasmine karma-runner karma-jasmine


    【解决方案1】:

    我已经弄清楚我的场景出了什么问题。让我解释一下:

    • 我的 app 模块有几个依赖项。
    • 我的字符串服务app模块的一部分。
    • 现在,当您想要测试 字符串服务 时,您必须在 karma.conf 中引用所有(意味着所有)app 模块依赖项。 js 文件部分。甚至是您不用于该服务的那些。
    • 就我而言,我没有引用 qrcode 依赖项,因为我没有在 字符串服务 中使用 qrcode
    • 而这个缺失的参考是造成问题的原因。因此 karma 无法实例化模块 app

    希望这对某人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      • 2017-04-09
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      • 2015-01-02
      相关资源
      最近更新 更多