Angularjs test with Jest module injection

Trying to test angular services with Jest and get this error:

[$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. 

How can I make fun of my "superag" module and make it accessible to mathService ?

Do I need to import an app.js file with a module declaration for every test I do?

Ps: I tried too hard with 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" } } 

math.service.js

 function MathService(){ var addTwoNumbers = function(x, y){ return x + y; }; return { addTwoNumbers }; } angular.module('superag').factory('mathservice', MathService); 

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); }); }); 
+5
source share
2 answers

This error occurs when you declare a dependency on a module that is not defined anywhere or has not been loaded in the current browser context.

If you receive this error, check the name of the module in question and whether the file in which this module is defined is loaded (either via the <script> , a loader, for example, require.js, or a test harness as karma).

A less common cause of this error is an attempt to β€œreopen” a module that is not yet defined.

To define a new module, call angular.module with a name and an array of dependent modules, for example:

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

To get a link to the same module for further configuration, call angular.module without an array argument.

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

A call to angular.module without an array of dependencies, when the module is not yet defined, causes this error. To fix this, define your module with a name and an empty array, as in the first example above.

+3
source

You need to load the module under test using the module function provided in angular -mocks, so it is available in your tests, for docs .

 beforeEach(module('superag')) 

Then you can enter your service.

+1
source

Source: https://habr.com/ru/post/1275970/


All Articles