4

I used to use HttpModule to fire ajax call and had a mockup backend to catch every request in the front-end for developing. Now I use HttpClientModule because I want to use the interceptor feature. But my mockup backend base on Http is not working. How can I modify my mockup backend to make it catch the call from HttpCleint.

fake-backend.ts

import { Http, BaseRequestOptions, Response, ResponseOptions, RequestMethod } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';
import { environment } from '../../environments/environment';

export function fakeBackendFactory(backend: MockBackend, options: 
BaseRequestOptions) {
    // configure fake backend
    backend.connections.subscribe((connection: MockConnection) => {
    let testUser = { username: 'test', password: 'test', firstName: 'Test', lastName: 'User' };

    // wrap in timeout to simulate server api call
    setTimeout(() => {

      // 
      if (connection.request.url.includes('/daquery/ws/setup') && connection.request.method === RequestMethod.Get) {
       ...
    }

    return new Http(backend, options);
}
etlds
  • 5,810
  • 2
  • 23
  • 30

1 Answers1

-1

In your test you are using Http, not the HttpClientModule, anyway to fake response from the httpclient in a test of a service, this is how I set it up the test.

import {TestBed, getTestBed} from '@angular/core/testing';
import {HttpClientTestingModule, HttpTestingController} from '@angular/common/http/testing';


 beforeEach(() => {
  TestBed.configureTestingModule({
    imports: [HttpClientTestingModule],
    providers: [AuthService]
  });

  authService = TestBed.get(AuthService);
  httpMock = TestBed.get(HttpTestingController);
});

it('should return user and token successfully at login', (done) => {
   const credentials = {userName: 'bob', password: '123'} as LoginPayload;
   const httpResponse = {user: user, token: '123'} as LoginSuccessPayload;

   authService.login(credentials).subscribe(res => {
     expect(res).toEqual(httpResponse);
     done();
   });

   const loginRequest = httpMock.expectOne('/api/auth/signin');
   loginRequest.flush(httpResponse);

   expect(loginRequest).toBeDefined();
   expect(loginRequest.request.method).toEqual('POST');

   httpMock.verify();
});
ramon22
  • 3,528
  • 2
  • 35
  • 48