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

谁都会走 提交于 2019-12-12 20:28:15

问题


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:


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.



来源:https://stackoverflow.com/questions/38234610/how-to-inject-ngroute-into-jasmine-karma-angularjs-unit-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!