HttpHeaders和lazyupdate Angular 4和Karma

时间:2017-09-26 15:41:41

标签: angular karma-jasmine angular4-httpclient

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

我能看到的唯一区别是在HttpHeaders对象中,恰好在lazyUpdate中。

无测试模式

enter image description here

有业力

enter image description here

代码:

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扩展它,类别服务没有特定代码)

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

}

有人可以解释一下吗?

1 个答案:

答案 0 :(得分:0)

在测试设置了一些请求标头的拦截器时,我遇到了类似的问题。我在测试中做错的是没有设置标头之一(留给undefined)-我没有深入研究Angular代码,但这似乎忽略了将'lazyInit'属性设置为{ {1}},该位置将停止触发“ init”调用(基本上设置了标头):

null

github上有一个问题涉及到此。请参阅this评论。