我在使用HttpHeaders (angular 4.3.0)和Karma时出现问题。我编写了一些测试,当我使用npm test 命令运行它们时,http请求未被授权,因为token(X-Auth-Token)未设置。但是当我在浏览器中使用控制台运行同样的代码时,X-Auth-Token已经设置,一切都正常工作。
我唯一能看到的区别就是HttpHeaders对象,具体地说是lazyUpdate。
非测试模式
Karma模式
代码:
category.service.spec.ts
describe('Service : Category', () => {
// setup
beforeEach(() => TestBed.configureTestingModule({
imports: [ HttpClientModule, LocalStorageModule.withConfig(localStorageConfig), TranslateModule.forRoot({
loader: { provide: TranslateLoader, useClass: TranslateFakeLoader }
})],
providers: [CategoryService, LoaderService, LocalStorageService
]
}));
it('should list the categories', () => {
let categoryService = TestBed.get(CategoryService);
categoryService.apiRoutes = ApiCategoryRoutes;
categoryService.modelName = "category";
let actualCategories = [];
// categoryService expends APIResolverService
let observable = categoryService.find();
observable.subscribe(data => {
actualCategories = data;
});
console.log("actualCategories");
console.log(actualCategories);
});
});
apiResolver.service.ts(categoryService 扩展自它,category service 没有特定的代码)
export abstract class APIResolverService {
...
public find() {
this.showLoader();
let url = this.getUrl(0, true);
let headers = this.setHttpHeaders();
console.log("headers");
console.log(headers);
let observable = this.http.get(url, {headers : headers})
.map(res => this.manageResponse(res, true, true)).share();
observable.subscribe(data => this.hideLoader(), error => this.hideLoader());
return observable;
}
...
public setHttpHeaders(){
let valueToken: string = JSON.stringify(this.localStorage.get('token'));
let myHeaders = new HttpHeaders()
.set('Content-Type', 'application/json')
.set('Accept', 'application/json')
.set('Accept-Language', "en")
.set('X-Auth-Token', valueToken.replace(/['"]+/g, ''));
return myHeaders;
}
}
有人能解释一下这个吗?