Angular 4.3 HttpClient with MockBackend

I used to use an HttpModule to launch an ajax call and had a mockup backend to catch every request in the development interface. Now I am using the HttpClientModule because I want to use the intercept function. But my layout database on Http does not work. How can I change the backend of the layout to make it catch a 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);
}
+4
source share
1 answer

In your test, you use Http, not HttpClientModule, anyway, to fake the response from httpclient in the service test, since I set it up for 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();
});
-1
source

Source: https://habr.com/ru/post/1687053/


All Articles