I am learning testing Angular 2 with Karma, and was wondering about some points in code I didn't understand. After the TestBed
"mock module" is configured, the following code runs:
mockBackend = getTestBed().get(MockBackend);
What does this do? I found the following explanation in another article: "gets a reference to the mock backend so we can respond with fake data when it is fetched with Http.get", but I don't see why I need to "get it", isn't it already there from import {MockBackend, MockConnection} from '@angular/http/testing';
? Or does the module get the method somehow?
I use it later like so...and still don't understand why I had to attach it to the test bed:
mockBackend.connections.subscribe(
(connection: MockConnection) => {
connection.mockRespond(new Response(
new ResponseOptions({
body: "lol data"
}
)));
});
In short, the actual question is - what does the first line of code I posted do?
Complete code, just for context:
import { TestBed, getTestBed, async, inject } from '@angular/core/testing';
import { Headers, BaseRequestOptions, Response, HttpModule, Http, XHRBackend, RequestMethod} from '@angular/http';
import {ResponseOptions} from '@angular/http';
import {MockBackend, MockConnection} from '@angular/http/testing';
import {FooHttpService} from '../../services/foo-service.service.ts';
describe('My Service Making an Http Call', () => {
let mockBackend: MockBackend;
beforeEach(async(() => {
TestBed.configureTestingModule({
providers: [
FooHttpService,
MockBackend,
BaseRequestOptions,
{
provide: Http,
deps: [MockBackend, BaseRequestOptions],
useFactory:
(backend: XHRBackend, defaultOptions: BaseRequestOptions) => {
return new Http(backend, defaultOptions);
}
}
],
imports: [
HttpModule
]
});
mockBackend = getTestBed().get(MockBackend);
TestBed.compileComponents();
}));
Code is taken from a tutorial here.