Before switching to HttpClient from Http, I had a simple setup using MockBacked. I had a mock-backend.provider.ts file that looked like this:
import { Http, BaseRequestOptions, Response, ResponseOptions, RequestMethod, XHRBackend, RequestOptions } from '@angular/http'; import { MockBackend, MockConnection } from '@angular/http/testing'; import { subscribers } from '../jsons/subscribers.json'; import { TokenService } from '../../authentication/token.service'; export function mockBackendFactory(backend: MockBackend, options: BaseRequestOptions, realBackend: XHRBackend) { // configure fake backend backend.connections.subscribe((connection: MockConnection) => { // wrap in timeout to simulate server api call setTimeout(() => { let url = connection.request.url; let method = connection.request.method; if (url.endsWith('/demographic/subscriber') && method === RequestMethod.Get) { let tokenService: TokenService = new TokenService(); // get username from token let username = tokenService.getUsername(); // find if any subscriber matches login credentials let filteredSubscriber = subscribers.filter(subscriber => { return subscriber.username === username; }); // check to see if the user exists if (filteredSubscriber.length) { let subscriber = filteredSubscriber[0]; connection.mockRespond(new Response(new ResponseOptions({ status: 200, body: { "subscriber": { "id": subscriber.id, "firstName": subscriber.firstName, "lastName": subscriber.lastName, "username": subscriber.username, "preferredEmail": subscriber.preferredEmail } } }))); } else { // else return 400 bad request connection.mockError(new Error('Unauthorized')); } return; }, 500); }); return new Http(backend, options); } export let MockBackendProvider = { provide: Http, useFactory: mockBackendFactory, deps: [MockBackend, BaseRequestOptions, XHRBackend] };
and in my core.module.ts file I would put MockBackendProvider in the "Providers" section.
This would allow me to quickly make fun of json responses, and I had a setting to switch this provider based on an environment variable.
When I switched to using HttpClient ... it no longer accepts the backend parameter directly, as it uses an HttpHandler, which accepts a backend, but I cannot force it to accept a MockBackend.
I do not believe that my current configuration can be done using HttpClient, and I am fine, but I have no idea how to configure the stream without changes with the new modules.
Any help would be greatly appreciated! If you need to see more code, please let me know.
angular
Shawn cain
source share