问题描述
我正在尝试使一个基本的单元测试示例正常工作.与此app.js一切正常
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('');
}
}]);
和此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
});
});
});
使用此业力文件配置
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'
]
当我尝试像这样将ngRoute注入app.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('');
}
}]);
在这种情况下,我会在业力中收到以下错误[更新:即使我没有如上所示将angular-mock.js库加载到业力中,也会发生此错误]
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)
那么...如何将ngRoute正确注入spec.js?我已经尝试了多种方法,但都无济于事.
So... how do I inject ngRoute into spec.js correctly? I've tried a variety of things, none of which worked.
推荐答案
显然,您会收到此错误,因为PhantomJS
无法实例化您的主要Angular模块whapp
.一种可能的原因是,文件node_modules/angular-mocks/angular-route/angular-route.js
丢失.
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.
很显然,您正在使用npm
来管理依赖项.因此,尝试将您的当前文件替换为:
Obviously, you are using npm
to manage your dependencies. So try to replace your current file with:
node_modules/angular-route/angular-route.js
与ui-route
模块相同:
node_modules/angular-ui-router/release/angular-ui-router.js
我希望这会对您有所帮助.
I hope this will help you.
这篇关于如何将ngRoute注入Jasmine/Karma AngularJS单元测试中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!