How to inject ngRoute in Jasmine / Karma AngularJS unit test?

I am trying to run a basic unit test example. It all works great with this app.js

var whapp = angular.module('whapp', [])
.filter('reverse',[function(){
    return function(string){
        return string.split('').reverse().join('');
    }
}]);

      

and this spec.js

describe('Filters', function(){ //describe your object type
    beforeEach(module('whapp')); //load module
    describe('reverse',function(){ //describe your app name
        var reverse, rootScope;
        beforeEach(inject(function($filter){ //initialize your filter
            reverse = $filter('reverse',{});
        }));
        it('Should reverse a string', function(){  //write tests
            expect(reverse('rahil')).toBe('lihar'); //pass
        });
    });
});

      

with this karma config

files: [
    'node_modules/angular/angular.js',
    'node_modules/angular-mocks/angular-mocks.js',
    'node_modules/angular-mocks/angular-route/angular-route.js',
    'node_modules/angular-mocks/angular-ui-router/release/angular-ui-router.js',
      'app/js/*.js',
      'tests/*.js'
]

      

The problem occurs when I try to inject ngRoute into my module in app.js, like this:

var whapp = angular.module('whapp', ['ngRoute'])
.filter('reverse',[function(){
    return function(string){
        return string.split('').reverse().join('');
    }
}]);

      

In this case, I get the following error in karma. [UPDATE: this error occurs even though I don't load angular-mock.js library in karma as shown above)

TypeError: undefined is not a constructor (evaluating 'reverse('rahil')') in tests/spec.js (line 9)

      

So ... how to properly inject ngRoute into spec.js? I tried various things, none of which worked.

+2


source to share


1 answer


Apparently you are getting this error because PhantomJS

your main Angular module cannot build whapp

. One possible reason is the missing file node_modules/angular-mocks/angular-route/angular-route.js

.

Obviously what you are using npm

to manage your dependencies. So try replacing the current file:

node_modules/angular-route/angular-route.js

      



The same for the module ui-route

:

node_modules/angular-ui-router/release/angular-ui-router.js

      

Hope this helps you.

+2


source







All Articles