我试图用Karma和Jasmine测试一个拦截器,但是出现意想不到的错误。我正在关注此代码:http://jbavari.github.io/blog/2014/06/20/testing-interceptor-headers-in-angularjs/
代码:
angular
.module('xos.helpers',[
'ngCookies',
'xos.xos',
'xos.hpcapi',
'xos.xoslib',
'bugSnag'
])
.config(config);
function config($httpProvider, $resourceProvider) {
console.log('xos.helpers config')
$httpProvider.interceptors.push('SetCSRFToken');
$interpolateProvider.startSymbol('{$');
$interpolateProvider.endSymbol('$}');
// NOTE http://www.masnun.com/2013/09/18/django-rest-framework-angularjs-resource-trailing-slash-problem.html
$resourceProvider.defaults.stripTrailingSlashes = false;
}
测试:
'use strict';
describe('The xos.helper module', function(){
var SetCSRFToken, httpProviderObj;
beforeEach(module('xos.helpers'));
beforeEach(module(function(_$httpProvider_){
httpProviderObj = _$httpProvider_;
}));
beforeEach(inject(function(_SetCSRFToken_){
SetCSRFToken = _SetCSRFToken_;
}));
it('should exist', () => {
expect(SetCSRFToken).toBeDefined();
});
it('should set SetCSRFToken interceptor', () => {
expect(httpProviderObj).toBeDefined();
expect(httpProviderObj.interceptors).toContain('SetCSRFToken');
});
});
在karma conf中,所有需要的文件都已加载,但我收到了这个未知错误:
/Users/teone/Sites/xos/views/ngXosLib/bower_components/angular/angular.js:4414:53
forEach@/Users/teone/Sites/xos/views/ngXosLib/bower_components/angular/angular.js:336:24
loadModules@/Users/teone/Sites/xos/views/ngXosLib/bower_components/angular/angular.js:4374:12
createInjector@/Users/teone/Sites/xos/views/ngXosLib/bower_components/angular/angular.js:4299:22
workFn@/Users/teone/Sites/xos/views/ngXosLib/bower_components/angular-mocks/angular-mocks.js:2427:60
Expected undefined to be defined.
/Users/teone/Sites/xos/views/ngXosLib/xosHelpers/spec/csrftoken.test.js:17:37
有什么想法吗?
答案 0 :(得分:3)
好的发现了这个问题。
我没有在ngResource
模块中注入xos.helpers
模块。在karma Chrome
部分添加PhantomJs
和browsers
部分会打印出一个有意义的错误来指导我。
答案 1 :(得分:0)
你需要使用inject来获取角度服务和提供者,试试这个:
describe('The xos.helper module', function(){
var SetCSRFToken, httpProviderObj;
beforeEach(module('xos.helpers'));
//Instead 'module' use 'inject'
beforeEach(inject(function($httpProvider){
httpProviderObj = $httpProvider;
}));
beforeEach(inject(function(_SetCSRFToken_){
SetCSRFToken = _SetCSRFToken_;
}));
it('should exist', () => {
expect(SetCSRFToken).toBeDefined();
});
it('should set SetCSRFToken interceptor', () => {
expect(httpProviderObj).toBeDefined();
expect(httpProviderObj.interceptors).toContain('SetCSRFToken');
});
});