AngularJS factory testing in karma with jasmine

I am trying to test an AngularJS application using Jasmine through Karma. I get this error (at least this is the last one):

Uncaught TypeError: Cannot read property '$modules' of null at /Users/benturner/Dropbox/Code/galapagus/app/static/js/angular-mocks.js:1866 

From my karma.conf.js:

 files: [ 'static/js/jquery.min.js', 'static/js/angular.min.js', 'static/js/angular-mocks.js', 'static/js/angular-resource.min.js', 'static/js/angular-scenario.js', 'static/js/angular-loader.min.js', 'static/js/momentous/ctrl_main.js', // contains all my app code 'test/momentous.js' ], 

Here is my test:

 (function () { "use strict"; var controller = null; var scope = null; describe("Services", inject(function($rootScope, Moments) { var mockedFactory, moments, flag, spy; moments = [{name: 'test'}]; beforeEach(module('momentous', function($provide) { scope = $rootScope.$new(); $provide.value('$rootScope', scope); mockedFactory = { getList: function() { return moments; } }; spy = jasmine.createSpy(mockedFactory.getList); $provide.value('Moments', mockedFactory); })); it('should return moments from the factory service', function() { runs(function() { console.log(scope.getList); flag = false; setTimeout(function() { scope.getList(); flag = true; }, 500); }); waitsFor(function() { return flag; }, "The call is done", 750); runs(function() { expect(scope.moments).toEqual([{name: 'test'}]); expect(spy).toHaveBeenCalled(); }); }); })); }()); 

So, I am trying to mock my factory service and check that it returns an array of objects and sets them to a variable in $ scope.

There's an asynchronous call there too, so I had to use run () and waitsFor ().

I still donโ€™t understand how I enter my scope $ scope so that I can test it, and using angular -mocks.js now gives me an error. I feel like I'm stepping back from this, no closer.

I combined this together from various stackoverflow docs, manuals and answers. Any directions? Thanks.

+6
source share
1 answer

I am also stuck in getting this exact error. My code is similar when I try to test the provider, so I call the module and pass it a function that configures the provider.

SOLVED:

I found that the problem is with the inject call to return the delegate to the describe method. You can only use injection to return the delegate to "it".

For instance:

 describe('something', inject(function(something) {})); // will throw the $module is null error 

But this will work:

 it('something', inject(function(something) {})); // works :) 
+10
source

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


All Articles