具有MockBackend的Angular 4.3 HttpClient

时间:2017-10-06 20:33:57

标签: angular angular4-httpclient

我曾经使用HttpModule来激活ajax调用,并有一个模型后端来捕获前端的每个请求以进行开发。 现在我使用HttpClientModule因为我想使用拦截器功能。但是基于Http的我的模型后端无效。 如何修改我的模型后端以使其捕获来自HttpCleint的调用。

假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);
}

1 个答案:

答案 0 :(得分:-1)

在您的测试中,您使用的是 Http ,而不是 HttpClientModule ,无论如何在服务测试中伪造来自httpclient的响应,这就是我设置它的方式测试。

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();
});