Angular 2 - Http-Testing - Error: “Cannot read property 'getCookie' of null”

China☆狼群 提交于 2020-01-13 12:00:11

问题


Always get this error in console, when running Jasmine Tests with karma on the following code:

Error:

TypeError: Cannot read property 'getCookie' of null

Service:

//http.service.ts
import {Injectable, Inject, ReflectiveInjector}    from '@angular/core';
import {Headers, Http, Response, HTTP_PROVIDERS} from '@angular/http';

import {Observable} from "rxjs";

const injector = ReflectiveInjector.resolveAndCreate(HTTP_PROVIDERS);
const http = injector.get(Http);

@Injectable()
export class HttpService {

  constructor() {}

  httpTest(){
    return http.get("https://jsonplaceholder.typicode.com/users")
        .map(response =>{ return response.json()});
  }
}

Testfile:

//http.service.spec.ts
import {
  it,
  describe,
  expect,
  inject,
  addProviders,
  beforeEach
} from '@angular/core/testing';
import {MockBackend, MockConnection} from '@angular/http/testing';
import {provide} from '@angular/core';
import {
  Http,
  BaseRequestOptions,
  Response,
  ResponseOptions
} from '@angular/http';


import { HttpService } from './http.service';

describe('Http-Test', () => {

  beforeEach(() => {
    addProviders([
      HttpService,
      BaseRequestOptions,
      MockBackend,
      {
        provide: Http,
        useFactory: (backend: MockBackend, defaultOptions: BaseRequestOptions) => {
          return new Http(backend, defaultOptions);
        },
        deps: [MockBackend, BaseRequestOptions]
      }
    ])
  });

  beforeEach(inject([MockBackend], (backend: MockBackend) => {
    const baseResponse = new Response(new ResponseOptions({ body: 'userListAsJSON' }));
    backend.connections.subscribe((c: MockConnection) => c.mockRespond(baseResponse));
  }));

  it('should return response when subscribed to httpTest',
    inject([HttpService], (testService: HttpService) => {
      testService.httpTest().subscribe((res: Response) => {
        expect(res.text()).toBe('userListAsJSON');
      });
    })
  );

})

Didn't finde anything why it can't "read property 'getCookie' of null", or why it tries to read it at all...


回答1:


Its a problem with XSRFStrategy provider.

Works if you create a fake XSRFStrategy in the test file and add as a provider.

class FakeXSRFStrategy implements XSRFStrategy {
  public configureRequest(req: Request) { /* */ }
}

const XRSF_MOCK = provide(XSRFStrategy, { useValue: new FakeXSRFStrategy() })


来源:https://stackoverflow.com/questions/39245831/angular-2-http-testing-error-cannot-read-property-getcookie-of-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!