Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular 2 Testing RxJS Observable with MockBackend and HTTP
import { async, inject, TestBed } from "@angular/core/testing";
import { Http, HttpModule, BaseRequestOptions, RequestMethod, Response, ResponseOptions } from "@angular/http";
import { MockBackend } from "@angular/http/testing";
import { Observable } from "rxjs";
import { MockSessionService } from "../../mocks/session.service.mock";
import { QMSService } from "./qms.service";
import { SessionService } from "../session/session.service";
class SetupTest {
static mockConnection(mockBackend: MockBackend) {
let options = new ResponseOptions({
body: JSON.stringify({ myData: "Something" })
});
mockBackend.connections.subscribe((c: any) => c.mockRespond(new Response(options)));
}
}
describe("QMSService", () => {
let qmsService: QMSService;
let sessionService: SessionService;
let backend: MockBackend;
let response: any;
let request: any;
let HTTP = {
provide: Http,
useFactory: (backend: MockBackend, options: BaseRequestOptions) => new Http(backend, options),
deps: [MockBackend, BaseRequestOptions]
}
// Set up mocks for Http backend and mock session service
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [
MockBackend,
BaseRequestOptions,
HTTP,
QMSService,
{ provide: SessionService, useClass: MockSessionService }
]
});
});
beforeEach(inject([QMSService, SessionService, MockBackend], (qs: QMSService, ss: SessionService, bkend: MockBackend) => {
qmsService = qs;
sessionService = ss;
backend = bkend;
}));
describe("createTraversal", () => {
it("should get a response", async(() => {
SetupTest.mockConnection(backend);
qmsService.createTraversal(123)
.subscribe((jsr: any) => response = jsr);
expect(response).toEqual({ myData: "Something" });
}));
});
describe("getCurrentQuestions", () => {
it("should get a response", async(() => {
SetupTest.mockConnection(backend);
qmsService.getCurrentQuestions("/api/current")
.subscribe((jsr: any) => response = jsr);
expect(response).toEqual({ myData: "Something" });
}));
});
describe("When answering a question", () => {
it("should return a response", async(() => {
SetupTest.mockConnection(backend);
qmsService.answerQuestion("/some_url", [{"some_key": "SOME_ANSWER"}])
.subscribe((jsr: any) => response = jsr);
expect(response).toEqual({ myData: "Something" });
}));
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment