【问题标题】:Angularjs test with Jest module injection使用 Jest 模块注入进行 Angularjs 测试
【发布时间】:2018-08-29 08:17:16
【问题描述】:

尝试使用 Jest 测试 Angular 服务并收到此错误:

[$injector:nomod] Module 'superag' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

如何模拟我的模块“superag”并提供给mathService

我是否必须在每次测试时都导入带有模块声明的 app.js 文件?

Ps.:我也试过beforeEach(module('superag')),但没有成功

package.json

"jest": {
    "collectCoverageFrom": [
      "**/*.{js}",
      "!**/node_modules/**"
    ]
  },
  "devDependencies": {
    "angular-mocks": "^1.6.9",
    "jest-cli": "^23.0.0-alpha.0"
  },
  "dependencies": {
    "angular": "^1.6.9"
  }
}

ma​​th.service.js

function MathService(){

    var addTwoNumbers = function(x, y){
      return x + y;
    };

    return {
      addTwoNumbers
    };
  }
angular.module('superag').factory('mathservice', MathService);

ma​​th.service.test.js

require('angular');
require('angular-mocks');
require('./math.service.js');

describe('Math service - addTwoNumbers', () => {

  beforeEach(
    angular.mock.module('superag')
  );

  var _mathservice;

  beforeEach(inject((mathservice) => {
    _mathservice = mathservice;
  }));

  it('1 + 1 should equal 2', () => {
    var actual = _mathservice.addTwoNumbers(1,1);
    expect(actual).toEqual(2);
  });

});

【问题讨论】:

    标签: angularjs testing jestjs


    【解决方案1】:

    当您声明对未在任何地方定义或未在当前浏览器上下文中加载的模块的依赖项时,会发生此错误。

    当您收到此错误时,请检查相关模块的名称是否正确以及定义此模块的文件是否已加载(通过 <script> 标签、加载器(如 require.js)或测试工具)像业力)。

    此错误的一个不太常见的原因是尝试“重新打开”尚未定义的模块。

    要定义新模块,请使用名称和依赖模块数组调用angular.module,如下所示:

    // When defining a module with no module dependencies,
    // the array of dependencies should be defined and empty.
    var myApp = angular.module('myApp', []);
    

    要检索对同一模块的引用以进行进一步配置,请调用不带数组参数的 angular.module。

    var myApp = angular.module('myApp');
    

    在尚未定义模块时调用 angular.module 而没有依赖数组会导致抛出此错误。要修复它,请使用名称和空数组定义您的模块,如上面的第一个示例所示。

    【讨论】:

    • 在我的测试中还是在我的服务中?
    • 已经尝试定义成BeforeEach但没有成功... :(
    • 试过beforeEach(module('superag'))beforeEach(angular.module('superag', []))
    • 如果你想模拟一个模块也许你可以试试这个beforeEach(function(){module('moduleToMock');module(function ($provide) {$provide.value('yourService', serviceMock);});});
    • 没有成功...I've created a repo我的尝试,你能看看吗?感谢您迄今为止所做的努力
    【解决方案2】:

    您需要使用 angular-mocks 中提供的模块功能加载被测模块,因此它在您的测试中可用,每 docs

    beforeEach(module('superag'))
    

    然后你可以注入你的服务。

    【讨论】:

    • superag 模块在哪里定义...你能提供一个小提琴吗?
    • 就是这样。我需要在测试中定义superag,不需要其他文件。
    • 感谢您的宝贵时间
    猜你喜欢
    • 2017-10-28
    • 2017-02-13
    • 2014-10-22
    • 2020-04-25
    • 2017-08-23
    • 2015-05-29
    • 2020-12-06
    • 2018-09-14
    • 2019-09-01
    相关资源
    最近更新 更多