feat(common): new HttpClient API
HttpClient is an evolution of the existing Angular HTTP API, which exists alongside of it in a separate package, @angular/common/http. This structure ensures that existing codebases can slowly migrate to the new API. The new API improves significantly on the ergonomics and features of the legacy API. A partial list of new features includes: * Typed, synchronous response body access, including support for JSON body types * JSON is an assumed default and no longer needs to be explicitly parsed * Interceptors allow middleware logic to be inserted into the pipeline * Immutable request/response objects * Progress events for both request upload and response download * Post-request verification & flush based testing framework
This commit is contained in:

committed by
Jason Aden

parent
2a7ebbe982
commit
37797e2b4e
49
packages/common/http/testing/src/api.ts
Normal file
49
packages/common/http/testing/src/api.ts
Normal file
@ -0,0 +1,49 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright Google Inc. All Rights Reserved.
|
||||
*
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {HttpRequest} from '@angular/common/http';
|
||||
|
||||
import {TestRequest} from './request';
|
||||
|
||||
/**
|
||||
* Defines a matcher for requests based on URL, method, or both.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
export interface RequestMatch {
|
||||
method?: string;
|
||||
url?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Controller to be injected into tests, that allows for mocking and flushing
|
||||
* of requests.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
export abstract class HttpTestingController {
|
||||
/**
|
||||
* Search for requests that match the given parameter, without any expectations.
|
||||
*/
|
||||
abstract match(match: string|RequestMatch|((req: HttpRequest<any>) => boolean)): TestRequest[];
|
||||
|
||||
// Expect that exactly one request matches the given parameter.
|
||||
abstract expectOne(url: string): TestRequest;
|
||||
abstract expectOne(params: RequestMatch): TestRequest;
|
||||
abstract expectOne(matchFn: ((req: HttpRequest<any>) => boolean)): TestRequest;
|
||||
abstract expectOne(match: string|RequestMatch|((req: HttpRequest<any>) => boolean)): TestRequest;
|
||||
|
||||
// Assert that no requests match the given parameter.
|
||||
abstract expectNone(url: string): void;
|
||||
abstract expectNone(params: RequestMatch): void;
|
||||
abstract expectNone(matchFn: ((req: HttpRequest<any>) => boolean)): void;
|
||||
abstract expectNone(match: string|RequestMatch|((req: HttpRequest<any>) => boolean)): void;
|
||||
|
||||
// Validate that all requests which were issued were flushed.
|
||||
abstract verify(opts?: {ignoreCancelled?: boolean}): void;
|
||||
}
|
124
packages/common/http/testing/src/backend.ts
Normal file
124
packages/common/http/testing/src/backend.ts
Normal file
@ -0,0 +1,124 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright Google Inc. All Rights Reserved.
|
||||
*
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {HttpBackend, HttpEvent, HttpEventType, HttpRequest} from '@angular/common/http';
|
||||
import {Injectable} from '@angular/core';
|
||||
import {Observable} from 'rxjs/Observable';
|
||||
import {Observer} from 'rxjs/Observer';
|
||||
import {startWith} from 'rxjs/operator/startWith';
|
||||
|
||||
import {HttpTestingController, RequestMatch} from './api';
|
||||
import {TestRequest} from './request';
|
||||
|
||||
|
||||
/**
|
||||
* A testing backend for `HttpClient` which both acts as an `HttpBackend`
|
||||
* and as the `HttpTestingController`.
|
||||
*
|
||||
* `HttpClientTestingBackend` works by keeping a list of all open requests.
|
||||
* As requests come in, they're added to the list. Users can assert that specific
|
||||
* requests were made and then flush them. In the end, a verify() method asserts
|
||||
* that no unexpected requests were made.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
@Injectable()
|
||||
export class HttpClientTestingBackend implements HttpBackend, HttpTestingController {
|
||||
/**
|
||||
* List of pending requests which have not yet been expected.
|
||||
*/
|
||||
private open: TestRequest[] = [];
|
||||
|
||||
/**
|
||||
* Handle an incoming request by queueing it in the list of open requests.
|
||||
*/
|
||||
handle(req: HttpRequest<any>): Observable<HttpEvent<any>> {
|
||||
return new Observable((observer: Observer<HttpEvent<any>>) => {
|
||||
const testReq = new TestRequest(req, observer);
|
||||
this.open.push(testReq);
|
||||
observer.next({type: HttpEventType.Sent});
|
||||
return () => { testReq._cancelled = true; };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to search for requests in the list of open requests.
|
||||
*/
|
||||
private _match(match: string|RequestMatch|((req: HttpRequest<any>) => boolean)): TestRequest[] {
|
||||
if (typeof match === 'string') {
|
||||
return this.open.filter(testReq => testReq.request.url === match);
|
||||
} else if (typeof match === 'function') {
|
||||
return this.open.filter(testReq => match(testReq.request));
|
||||
} else {
|
||||
return this.open.filter(
|
||||
testReq => (!match.method || testReq.request.method === match.method.toUpperCase()) &&
|
||||
(!match.url || testReq.request.url === match.url));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for requests in the list of open requests, and return all that match
|
||||
* without asserting anything about the number of matches.
|
||||
*/
|
||||
match(match: string|RequestMatch|((req: HttpRequest<any>) => boolean)): TestRequest[] {
|
||||
const results = this._match(match);
|
||||
results.forEach(result => {
|
||||
const index = this.open.indexOf(result);
|
||||
if (index !== -1) {
|
||||
this.open.splice(index, 1);
|
||||
}
|
||||
});
|
||||
return results;
|
||||
}
|
||||
|
||||
/**
|
||||
* Expect that a single outstanding request matches the given matcher, and return
|
||||
* it.
|
||||
*
|
||||
* Requests returned through this API will no longer be in the list of open requests,
|
||||
* and thus will not match twice.
|
||||
*/
|
||||
expectOne(match: string|RequestMatch|((req: HttpRequest<any>) => boolean)): TestRequest {
|
||||
const matches = this.match(match);
|
||||
if (matches.length > 1) {
|
||||
throw new Error(`Expected one matching request, found ${matches.length} requests.`);
|
||||
}
|
||||
if (matches.length === 0) {
|
||||
throw new Error(`Expected one matching request, found none.`);
|
||||
}
|
||||
return matches[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Expect that no outstanding requests match the given matcher, and throw an error
|
||||
* if any do.
|
||||
*/
|
||||
expectNone(match: string|RequestMatch|((req: HttpRequest<any>) => boolean)): void {
|
||||
const matches = this.match(match);
|
||||
if (matches.length > 0) {
|
||||
throw new Error(`Expected zero matching requests, found ${matches.length}.`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that there are no outstanding requests.
|
||||
*/
|
||||
verify(opts: {ignoreCancelled?: boolean} = {}): void {
|
||||
let open = this.open;
|
||||
// It's possible that some requests may be cancelled, and this is expected.
|
||||
// The user can ask to ignore open requests which have been cancelled.
|
||||
if (opts.ignoreCancelled) {
|
||||
open = open.filter(testReq => !testReq.cancelled);
|
||||
}
|
||||
if (open.length > 0) {
|
||||
// Show the URLs of open requests in the error, for convenience.
|
||||
const urls = open.map(testReq => testReq.request.url.split('?')[0]).join(', ');
|
||||
throw new Error(`Expected no open requests, found ${open.length}: ${urls}`);
|
||||
}
|
||||
}
|
||||
}
|
34
packages/common/http/testing/src/module.ts
Normal file
34
packages/common/http/testing/src/module.ts
Normal file
@ -0,0 +1,34 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright Google Inc. All Rights Reserved.
|
||||
*
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {HttpBackend, HttpClientModule} from '@angular/common/http';
|
||||
import {NgModule} from '@angular/core';
|
||||
|
||||
import {HttpTestingController} from './api';
|
||||
import {HttpClientTestingBackend} from './backend';
|
||||
|
||||
|
||||
/**
|
||||
* Configures `HttpClientTestingBackend` as the `HttpBackend` used by `HttpClient`.
|
||||
*
|
||||
* Inject `HttpTestingController` to expect and flush requests in your tests.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
@NgModule({
|
||||
imports: [
|
||||
HttpClientModule,
|
||||
],
|
||||
providers: [
|
||||
HttpClientTestingBackend,
|
||||
{provide: HttpBackend, useExisting: HttpClientTestingBackend},
|
||||
{provide: HttpTestingController, useExisting: HttpClientTestingBackend},
|
||||
],
|
||||
})
|
||||
export class HttpClientTestingModule {
|
||||
}
|
200
packages/common/http/testing/src/request.ts
Normal file
200
packages/common/http/testing/src/request.ts
Normal file
@ -0,0 +1,200 @@
|
||||
/**
|
||||
* @license
|
||||
* Copyright Google Inc. All Rights Reserved.
|
||||
*
|
||||
* Use of this source code is governed by an MIT-style license that can be
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {HttpErrorResponse, HttpEvent, HttpEventType, HttpHeaders, HttpRequest, HttpResponse} from '@angular/common/http';
|
||||
import {Observer} from 'rxjs/Observer';
|
||||
|
||||
/**
|
||||
* A mock requests that was received and is ready to be answered.
|
||||
*
|
||||
* This interface allows access to the underlying `HttpRequest`, and allows
|
||||
* responding with `HttpEvent`s or `HttpErrorResponse`s.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
export class TestRequest {
|
||||
/**
|
||||
* Whether the request was cancelled after it was sent.
|
||||
*/
|
||||
get cancelled(): boolean { return this._cancelled; }
|
||||
|
||||
/**
|
||||
* @internal set by `HttpClientTestingBackend`
|
||||
*/
|
||||
_cancelled = false;
|
||||
|
||||
constructor(public request: HttpRequest<any>, private observer: Observer<HttpEvent<any>>) {}
|
||||
|
||||
|
||||
flush(body: ArrayBuffer|Blob|string|number|Object|(string|number|Object|null)[]|null, opts: {
|
||||
headers?: HttpHeaders | {[name: string]: string | string[]},
|
||||
status?: number,
|
||||
statusText?: string,
|
||||
} = {}): void {
|
||||
if (this.cancelled) {
|
||||
throw new Error(`Cannot flush a cancelled request.`);
|
||||
}
|
||||
const url = this.request.url;
|
||||
const headers =
|
||||
(opts.headers instanceof HttpHeaders) ? opts.headers : new HttpHeaders(opts.headers);
|
||||
body = _maybeConvertBody(this.request.responseType, body);
|
||||
let statusText: string|undefined = opts.statusText;
|
||||
let status: number = opts.status !== undefined ? opts.status : 200;
|
||||
if (opts.status === undefined) {
|
||||
if (body === null) {
|
||||
status = 204;
|
||||
statusText = statusText || 'No Content';
|
||||
} else {
|
||||
statusText = statusText || 'OK';
|
||||
}
|
||||
}
|
||||
if (statusText === undefined) {
|
||||
throw new Error('statusText is required when setting a custom status.');
|
||||
}
|
||||
const res = {body, headers, status, statusText, url};
|
||||
if (status >= 200 && status < 300) {
|
||||
this.observer.next(new HttpResponse<any>(res));
|
||||
this.observer.complete();
|
||||
} else {
|
||||
this.observer.error(new HttpErrorResponse(res));
|
||||
}
|
||||
}
|
||||
|
||||
error(error: ErrorEvent, opts: {
|
||||
headers?: HttpHeaders | {[name: string]: string | string[]},
|
||||
status?: number,
|
||||
statusText?: string,
|
||||
} = {}): void {
|
||||
if (this.cancelled) {
|
||||
throw new Error(`Cannot return an error for a cancelled request.`);
|
||||
}
|
||||
if (opts.status && opts.status >= 200 && opts.status < 300) {
|
||||
throw new Error(`error() called with a successful status.`);
|
||||
}
|
||||
const headers =
|
||||
(opts.headers instanceof HttpHeaders) ? opts.headers : new HttpHeaders(opts.headers);
|
||||
this.observer.error(new HttpErrorResponse({
|
||||
error,
|
||||
headers,
|
||||
status: opts.status || 0,
|
||||
statusText: opts.statusText || '',
|
||||
url: this.request.url,
|
||||
}));
|
||||
}
|
||||
|
||||
event(event: HttpEvent<any>): void {
|
||||
if (this.cancelled) {
|
||||
throw new Error(`Cannot send events to a cancelled request.`);
|
||||
}
|
||||
this.observer.next(event);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Helper function to convert a response body to an ArrayBuffer.
|
||||
*/
|
||||
function _toArrayBufferBody(
|
||||
body: ArrayBuffer | Blob | string | number | Object |
|
||||
(string | number | Object | null)[]): ArrayBuffer {
|
||||
if (typeof ArrayBuffer === 'undefined') {
|
||||
throw new Error('ArrayBuffer responses are not supported on this platform.');
|
||||
}
|
||||
if (body instanceof ArrayBuffer) {
|
||||
return body;
|
||||
}
|
||||
throw new Error('Automatic conversion to ArrayBuffer is not supported for response type.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to convert a response body to a Blob.
|
||||
*/
|
||||
function _toBlob(
|
||||
body: ArrayBuffer | Blob | string | number | Object |
|
||||
(string | number | Object | null)[]): Blob {
|
||||
if (typeof Blob === 'undefined') {
|
||||
throw new Error('Blob responses are not supported on this platform.');
|
||||
}
|
||||
if (body instanceof Blob) {
|
||||
return body;
|
||||
}
|
||||
if (ArrayBuffer && body instanceof ArrayBuffer) {
|
||||
return new Blob([body]);
|
||||
}
|
||||
throw new Error('Automatic conversion to Blob is not supported for response type.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to convert a response body to JSON data.
|
||||
*/
|
||||
function _toJsonBody(
|
||||
body: ArrayBuffer | Blob | string | number | Object | (string | number | Object | null)[],
|
||||
format: string = 'JSON'): Object|string|number|(Object | string | number)[] {
|
||||
if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) {
|
||||
throw new Error(`Automatic conversion to ${format} is not supported for ArrayBuffers.`);
|
||||
}
|
||||
if (typeof Blob !== 'undefined' && body instanceof Blob) {
|
||||
throw new Error(`Automatic conversion to ${format} is not supported for Blobs.`);
|
||||
}
|
||||
if (typeof body === 'string' || typeof body === 'number' || typeof body === 'object' ||
|
||||
Array.isArray(body)) {
|
||||
return body;
|
||||
}
|
||||
throw new Error(`Automatic conversion to ${format} is not supported for response type.`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to convert a response body to a string.
|
||||
*/
|
||||
function _toTextBody(
|
||||
body: ArrayBuffer | Blob | string | number | Object |
|
||||
(string | number | Object | null)[]): string {
|
||||
if (typeof body === 'string') {
|
||||
return body;
|
||||
}
|
||||
if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) {
|
||||
throw new Error('Automatic conversion to text is not supported for ArrayBuffers.');
|
||||
}
|
||||
if (typeof Blob !== 'undefined' && body instanceof Blob) {
|
||||
throw new Error('Automatic conversion to text is not supported for Blobs.');
|
||||
}
|
||||
return JSON.stringify(_toJsonBody(body, 'text'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a response body to the requested type.
|
||||
*/
|
||||
function _maybeConvertBody(
|
||||
responseType: string, body: ArrayBuffer | Blob | string | number | Object |
|
||||
(string | number | Object | null)[] | null): ArrayBuffer|Blob|string|number|Object|
|
||||
(string | number | Object | null)[]|null {
|
||||
switch (responseType) {
|
||||
case 'arraybuffer':
|
||||
if (body === null) {
|
||||
return null;
|
||||
}
|
||||
return _toArrayBufferBody(body);
|
||||
case 'blob':
|
||||
if (body === null) {
|
||||
return null;
|
||||
}
|
||||
return _toBlob(body);
|
||||
case 'json':
|
||||
if (body === null) {
|
||||
return 'null';
|
||||
}
|
||||
return _toJsonBody(body);
|
||||
case 'text':
|
||||
if (body === null) {
|
||||
return null;
|
||||
}
|
||||
return _toTextBody(body);
|
||||
default:
|
||||
throw new Error(`Unsupported responseType: ${responseType}`);
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user