javascript – Angular 2 – Http-Testing – 错误:“无法读取属性’getCookie’的null”

在以下代码中使用karma运行Jasmine Tests时,总是在控制台中出现此错误:

错误:

TypeError: Cannot read property ‘getCookie’ of null

服务:

//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');
      });
    })
  );

})

没有找到任何为什么它不能“读取属性’getCookie’的null”,或者为什么它试图读取它…

最佳答案 它是XSRFStrategy提供商的问题.

如果您在测试文件中创建假的XSRFStrategy并添加为提供程序,则可以正常工作.

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

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