How to inject ngRoute into Jasmine / Karma Angular

2019-07-08 02:37发布

I'm trying to get a basic unit test example working. It all works fine 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 files 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 so

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

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

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

So... how do I inject ngRoute into spec.js correctly? I've tried a variety of things, none of which worked.

1条回答
冷血范
2楼-- · 2019-07-08 03:19

Apparently, you get this error because PhantomJS fails to instantiate your main Angular module whapp. One possible reason is, that the file node_modules/angular-mocks/angular-route/angular-route.js is missing.

Obviously, you are using npm to manage your dependencies. So try to replace your current file with:

node_modules/angular-route/angular-route.js

The same for the ui-route module:

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

I hope this will help you.

查看更多
登录 后发表回答