2017-10-06 91 views
4

我曾經使用HttpModule來觸發ajax調用,並有一個模型後端來捕獲前端開發中的每個請求。 現在我使用HttpClientModule,因爲我想使用攔截器功能。但是基於Http的我的樣機後臺無法正常工作。 我該如何修改我的樣機後臺,使其捕獲來自HttpCleint的呼叫。Angular 4.3具有MockBackend的HttpClient

假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

在您的測試使用的是的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(); 
}); 
相關問題