问题
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