Rog*_*mos 6 testing angularjs jest
尝试使用Jest测试角度服务并得到此错误:
[$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.
Run Code Online (Sandbox Code Playgroud)
如何模拟我的模块'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"
}
}
Run Code Online (Sandbox Code Playgroud)
math.service.js
function MathService(){
var addTwoNumbers = function(x, y){
return x + y;
};
return {
addTwoNumbers
};
}
angular.module('superag').factory('mathservice', MathService);
Run Code Online (Sandbox Code Playgroud)
math.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);
});
});
Run Code Online (Sandbox Code Playgroud)
当您声明未在任何地方定义或未在当前浏览器上下文中加载的模块上的依赖项时,会发生此错误。
收到此错误时,请检查相关模块的名称是否正确,以及是否已加载定义了该模块的文件(通过<script>标签,诸如require.js之类的loader或诸如karma之类的测试工具)的加载。
此错误的一个不太常见的原因是尝试“重新打开”尚未定义的模块。
要定义一个新模块,请angular.module使用一个名称和一个依赖模块数组来调用,如下所示:
// When defining a module with no module dependencies,
// the array of dependencies should be defined and empty.
var myApp = angular.module('myApp', []);
Run Code Online (Sandbox Code Playgroud)
要检索对相同模块的引用以进行进一步配置,请在不使用array参数的情况下调用angular.module。
var myApp = angular.module('myApp');
Run Code Online (Sandbox Code Playgroud)
angular.module如果尚未定义模块,则在没有依赖项数组的情况下进行调用会导致引发此错误。要对其进行修复,请像上面的第一个示例一样,使用名称和一个空数组定义模块。
小智 1
您需要使用 Angular-Mocks 中提供的模块函数加载被测模块,以便根据文档在您的测试中可用。
beforeEach(module('superag'))
Run Code Online (Sandbox Code Playgroud)
然后你就可以注入你的服务了。