gpt4 book ai didi

angular - HttpHeaders 和 lazyupdate Angular 4 和 Karma

转载 作者:太空狗 更新时间:2023-10-29 17:28:51 27 4
gpt4 key购买 nike

我对 HttpHeaders (angular 4.3.0) 和 Karma 有疑问。我编写了一些测试,当我使用 npm test 命令运行它们时,http 查询是未经授权的,因为未设置 token (X-Auth-Token)。当我使用控制台在浏览器中运行相同的部分时,X-Auth-Token 已设置并且一切正常。

我能看到的唯一区别是 HttpHeaders 对象和 lazyUpdate。

无测试模式

enter image description here

karma 报应

enter image description here

代码:

类别.服务.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对其进行扩展,类目服务无具体代码)

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;
}

}

有人可以解释一下吗?

最佳答案

我在测试设置一些请求 header 的拦截器时遇到了类似的问题。我在测试期间做错的是没有设置标题之一(保留它 undefined)——我没有深入研究 Angular 代码,但这似乎遗漏了“lazyInit”属性设置为 null,这将停止触发“init”调用(基本上设置 header ):

    HttpHeaders.prototype.init = function () {
var _this = this;
if (!!this.lazyInit) {
if (this.lazyInit instanceof HttpHeaders) {
this.copyFrom(this.lazyInit);
}
else {
this.lazyInit();
}
this.lazyInit = null;
if (!!this.lazyUpdate) {
this.lazyUpdate.forEach(function (update) { return _this.applyUpdate(update); });
this.lazyUpdate = null;
}
}
};

github 上有一个问题与此有关。参见 this评论。

关于angular - HttpHeaders 和 lazyupdate Angular 4 和 Karma,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46430711/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com