UNPKG

18.2 kBJavaScriptView Raw
1/**
2 * @license Angular v8.2.0
3 * (c) 2010-2019 Google LLC. https://angular.io/
4 * License: MIT
5 */
6
7(function (global, factory) {
8 typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/common/http'), require('@angular/core'), require('rxjs')) :
9 typeof define === 'function' && define.amd ? define('@angular/common/http/testing', ['exports', '@angular/common/http', '@angular/core', 'rxjs'], factory) :
10 (global = global || self, factory((global.ng = global.ng || {}, global.ng.common = global.ng.common || {}, global.ng.common.http = global.ng.common.http || {}, global.ng.common.http.testing = {}), global.ng.common.http, global.ng.core, global.rxjs));
11}(this, function (exports, http, core, rxjs) { 'use strict';
12
13 /**
14 * @license
15 * Copyright Google Inc. All Rights Reserved.
16 *
17 * Use of this source code is governed by an MIT-style license that can be
18 * found in the LICENSE file at https://angular.io/license
19 */
20 /**
21 * Controller to be injected into tests, that allows for mocking and flushing
22 * of requests.
23 *
24 * @publicApi
25 */
26 var HttpTestingController = /** @class */ (function () {
27 function HttpTestingController() {
28 }
29 return HttpTestingController;
30 }());
31
32 /*! *****************************************************************************
33 Copyright (c) Microsoft Corporation. All rights reserved.
34 Licensed under the Apache License, Version 2.0 (the "License"); you may not use
35 this file except in compliance with the License. You may obtain a copy of the
36 License at http://www.apache.org/licenses/LICENSE-2.0
37
38 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
39 KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
40 WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
41 MERCHANTABLITY OR NON-INFRINGEMENT.
42
43 See the Apache Version 2.0 License for specific language governing permissions
44 and limitations under the License.
45 ***************************************************************************** */
46
47 function __decorate(decorators, target, key, desc) {
48 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
49 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
50 else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
51 return c > 3 && r && Object.defineProperty(target, key, r), r;
52 }
53
54 /**
55 * @license
56 * Copyright Google Inc. All Rights Reserved.
57 *
58 * Use of this source code is governed by an MIT-style license that can be
59 * found in the LICENSE file at https://angular.io/license
60 */
61 /**
62 * A mock requests that was received and is ready to be answered.
63 *
64 * This interface allows access to the underlying `HttpRequest`, and allows
65 * responding with `HttpEvent`s or `HttpErrorResponse`s.
66 *
67 * @publicApi
68 */
69 var TestRequest = /** @class */ (function () {
70 function TestRequest(request, observer) {
71 this.request = request;
72 this.observer = observer;
73 /**
74 * @internal set by `HttpClientTestingBackend`
75 */
76 this._cancelled = false;
77 }
78 Object.defineProperty(TestRequest.prototype, "cancelled", {
79 /**
80 * Whether the request was cancelled after it was sent.
81 */
82 get: function () { return this._cancelled; },
83 enumerable: true,
84 configurable: true
85 });
86 /**
87 * Resolve the request by returning a body plus additional HTTP information (such as response
88 * headers) if provided.
89 * If the request specifies an expected body type, the body is converted into the requested type.
90 * Otherwise, the body is converted to `JSON` by default.
91 *
92 * Both successful and unsuccessful responses can be delivered via `flush()`.
93 */
94 TestRequest.prototype.flush = function (body, opts) {
95 if (opts === void 0) { opts = {}; }
96 if (this.cancelled) {
97 throw new Error("Cannot flush a cancelled request.");
98 }
99 var url = this.request.urlWithParams;
100 var headers = (opts.headers instanceof http.HttpHeaders) ? opts.headers : new http.HttpHeaders(opts.headers);
101 body = _maybeConvertBody(this.request.responseType, body);
102 var statusText = opts.statusText;
103 var status = opts.status !== undefined ? opts.status : 200;
104 if (opts.status === undefined) {
105 if (body === null) {
106 status = 204;
107 statusText = statusText || 'No Content';
108 }
109 else {
110 statusText = statusText || 'OK';
111 }
112 }
113 if (statusText === undefined) {
114 throw new Error('statusText is required when setting a custom status.');
115 }
116 if (status >= 200 && status < 300) {
117 this.observer.next(new http.HttpResponse({ body: body, headers: headers, status: status, statusText: statusText, url: url }));
118 this.observer.complete();
119 }
120 else {
121 this.observer.error(new http.HttpErrorResponse({ error: body, headers: headers, status: status, statusText: statusText, url: url }));
122 }
123 };
124 /**
125 * Resolve the request by returning an `ErrorEvent` (e.g. simulating a network failure).
126 */
127 TestRequest.prototype.error = function (error, opts) {
128 if (opts === void 0) { opts = {}; }
129 if (this.cancelled) {
130 throw new Error("Cannot return an error for a cancelled request.");
131 }
132 if (opts.status && opts.status >= 200 && opts.status < 300) {
133 throw new Error("error() called with a successful status.");
134 }
135 var headers = (opts.headers instanceof http.HttpHeaders) ? opts.headers : new http.HttpHeaders(opts.headers);
136 this.observer.error(new http.HttpErrorResponse({
137 error: error,
138 headers: headers,
139 status: opts.status || 0,
140 statusText: opts.statusText || '',
141 url: this.request.urlWithParams,
142 }));
143 };
144 /**
145 * Deliver an arbitrary `HttpEvent` (such as a progress event) on the response stream for this
146 * request.
147 */
148 TestRequest.prototype.event = function (event) {
149 if (this.cancelled) {
150 throw new Error("Cannot send events to a cancelled request.");
151 }
152 this.observer.next(event);
153 };
154 return TestRequest;
155 }());
156 /**
157 * Helper function to convert a response body to an ArrayBuffer.
158 */
159 function _toArrayBufferBody(body) {
160 if (typeof ArrayBuffer === 'undefined') {
161 throw new Error('ArrayBuffer responses are not supported on this platform.');
162 }
163 if (body instanceof ArrayBuffer) {
164 return body;
165 }
166 throw new Error('Automatic conversion to ArrayBuffer is not supported for response type.');
167 }
168 /**
169 * Helper function to convert a response body to a Blob.
170 */
171 function _toBlob(body) {
172 if (typeof Blob === 'undefined') {
173 throw new Error('Blob responses are not supported on this platform.');
174 }
175 if (body instanceof Blob) {
176 return body;
177 }
178 if (ArrayBuffer && body instanceof ArrayBuffer) {
179 return new Blob([body]);
180 }
181 throw new Error('Automatic conversion to Blob is not supported for response type.');
182 }
183 /**
184 * Helper function to convert a response body to JSON data.
185 */
186 function _toJsonBody(body, format) {
187 if (format === void 0) { format = 'JSON'; }
188 if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) {
189 throw new Error("Automatic conversion to " + format + " is not supported for ArrayBuffers.");
190 }
191 if (typeof Blob !== 'undefined' && body instanceof Blob) {
192 throw new Error("Automatic conversion to " + format + " is not supported for Blobs.");
193 }
194 if (typeof body === 'string' || typeof body === 'number' || typeof body === 'object' ||
195 Array.isArray(body)) {
196 return body;
197 }
198 throw new Error("Automatic conversion to " + format + " is not supported for response type.");
199 }
200 /**
201 * Helper function to convert a response body to a string.
202 */
203 function _toTextBody(body) {
204 if (typeof body === 'string') {
205 return body;
206 }
207 if (typeof ArrayBuffer !== 'undefined' && body instanceof ArrayBuffer) {
208 throw new Error('Automatic conversion to text is not supported for ArrayBuffers.');
209 }
210 if (typeof Blob !== 'undefined' && body instanceof Blob) {
211 throw new Error('Automatic conversion to text is not supported for Blobs.');
212 }
213 return JSON.stringify(_toJsonBody(body, 'text'));
214 }
215 /**
216 * Convert a response body to the requested type.
217 */
218 function _maybeConvertBody(responseType, body) {
219 if (body === null) {
220 return null;
221 }
222 switch (responseType) {
223 case 'arraybuffer':
224 return _toArrayBufferBody(body);
225 case 'blob':
226 return _toBlob(body);
227 case 'json':
228 return _toJsonBody(body);
229 case 'text':
230 return _toTextBody(body);
231 default:
232 throw new Error("Unsupported responseType: " + responseType);
233 }
234 }
235
236 /**
237 * @license
238 * Copyright Google Inc. All Rights Reserved.
239 *
240 * Use of this source code is governed by an MIT-style license that can be
241 * found in the LICENSE file at https://angular.io/license
242 */
243 /**
244 * A testing backend for `HttpClient` which both acts as an `HttpBackend`
245 * and as the `HttpTestingController`.
246 *
247 * `HttpClientTestingBackend` works by keeping a list of all open requests.
248 * As requests come in, they're added to the list. Users can assert that specific
249 * requests were made and then flush them. In the end, a verify() method asserts
250 * that no unexpected requests were made.
251 *
252 *
253 */
254 var HttpClientTestingBackend = /** @class */ (function () {
255 function HttpClientTestingBackend() {
256 /**
257 * List of pending requests which have not yet been expected.
258 */
259 this.open = [];
260 }
261 /**
262 * Handle an incoming request by queueing it in the list of open requests.
263 */
264 HttpClientTestingBackend.prototype.handle = function (req) {
265 var _this = this;
266 return new rxjs.Observable(function (observer) {
267 var testReq = new TestRequest(req, observer);
268 _this.open.push(testReq);
269 observer.next({ type: http.HttpEventType.Sent });
270 return function () { testReq._cancelled = true; };
271 });
272 };
273 /**
274 * Helper function to search for requests in the list of open requests.
275 */
276 HttpClientTestingBackend.prototype._match = function (match) {
277 if (typeof match === 'string') {
278 return this.open.filter(function (testReq) { return testReq.request.urlWithParams === match; });
279 }
280 else if (typeof match === 'function') {
281 return this.open.filter(function (testReq) { return match(testReq.request); });
282 }
283 else {
284 return this.open.filter(function (testReq) { return (!match.method || testReq.request.method === match.method.toUpperCase()) &&
285 (!match.url || testReq.request.urlWithParams === match.url); });
286 }
287 };
288 /**
289 * Search for requests in the list of open requests, and return all that match
290 * without asserting anything about the number of matches.
291 */
292 HttpClientTestingBackend.prototype.match = function (match) {
293 var _this = this;
294 var results = this._match(match);
295 results.forEach(function (result) {
296 var index = _this.open.indexOf(result);
297 if (index !== -1) {
298 _this.open.splice(index, 1);
299 }
300 });
301 return results;
302 };
303 /**
304 * Expect that a single outstanding request matches the given matcher, and return
305 * it.
306 *
307 * Requests returned through this API will no longer be in the list of open requests,
308 * and thus will not match twice.
309 */
310 HttpClientTestingBackend.prototype.expectOne = function (match, description) {
311 description = description || this.descriptionFromMatcher(match);
312 var matches = this.match(match);
313 if (matches.length > 1) {
314 throw new Error("Expected one matching request for criteria \"" + description + "\", found " + matches.length + " requests.");
315 }
316 if (matches.length === 0) {
317 throw new Error("Expected one matching request for criteria \"" + description + "\", found none.");
318 }
319 return matches[0];
320 };
321 /**
322 * Expect that no outstanding requests match the given matcher, and throw an error
323 * if any do.
324 */
325 HttpClientTestingBackend.prototype.expectNone = function (match, description) {
326 description = description || this.descriptionFromMatcher(match);
327 var matches = this.match(match);
328 if (matches.length > 0) {
329 throw new Error("Expected zero matching requests for criteria \"" + description + "\", found " + matches.length + ".");
330 }
331 };
332 /**
333 * Validate that there are no outstanding requests.
334 */
335 HttpClientTestingBackend.prototype.verify = function (opts) {
336 if (opts === void 0) { opts = {}; }
337 var open = this.open;
338 // It's possible that some requests may be cancelled, and this is expected.
339 // The user can ask to ignore open requests which have been cancelled.
340 if (opts.ignoreCancelled) {
341 open = open.filter(function (testReq) { return !testReq.cancelled; });
342 }
343 if (open.length > 0) {
344 // Show the methods and URLs of open requests in the error, for convenience.
345 var requests = open.map(function (testReq) {
346 var url = testReq.request.urlWithParams.split('?')[0];
347 var method = testReq.request.method;
348 return method + " " + url;
349 })
350 .join(', ');
351 throw new Error("Expected no open requests, found " + open.length + ": " + requests);
352 }
353 };
354 HttpClientTestingBackend.prototype.descriptionFromMatcher = function (matcher) {
355 if (typeof matcher === 'string') {
356 return "Match URL: " + matcher;
357 }
358 else if (typeof matcher === 'object') {
359 var method = matcher.method || '(any)';
360 var url = matcher.url || '(any)';
361 return "Match method: " + method + ", URL: " + url;
362 }
363 else {
364 return "Match by function: " + matcher.name;
365 }
366 };
367 HttpClientTestingBackend = __decorate([
368 core.Injectable()
369 ], HttpClientTestingBackend);
370 return HttpClientTestingBackend;
371 }());
372
373 /**
374 * @license
375 * Copyright Google Inc. All Rights Reserved.
376 *
377 * Use of this source code is governed by an MIT-style license that can be
378 * found in the LICENSE file at https://angular.io/license
379 */
380 /**
381 * Configures `HttpClientTestingBackend` as the `HttpBackend` used by `HttpClient`.
382 *
383 * Inject `HttpTestingController` to expect and flush requests in your tests.
384 *
385 * @publicApi
386 */
387 var HttpClientTestingModule = /** @class */ (function () {
388 function HttpClientTestingModule() {
389 }
390 HttpClientTestingModule = __decorate([
391 core.NgModule({
392 imports: [
393 http.HttpClientModule,
394 ],
395 providers: [
396 HttpClientTestingBackend,
397 { provide: http.HttpBackend, useExisting: HttpClientTestingBackend },
398 { provide: HttpTestingController, useExisting: HttpClientTestingBackend },
399 ],
400 })
401 ], HttpClientTestingModule);
402 return HttpClientTestingModule;
403 }());
404
405 /**
406 * @license
407 * Copyright Google Inc. All Rights Reserved.
408 *
409 * Use of this source code is governed by an MIT-style license that can be
410 * found in the LICENSE file at https://angular.io/license
411 */
412
413 /**
414 * @license
415 * Copyright Google Inc. All Rights Reserved.
416 *
417 * Use of this source code is governed by an MIT-style license that can be
418 * found in the LICENSE file at https://angular.io/license
419 */
420
421 /**
422 * Generated bundle index. Do not edit.
423 */
424
425 exports.ɵangular_packages_common_http_testing_testing_a = HttpClientTestingBackend;
426 exports.HttpTestingController = HttpTestingController;
427 exports.HttpClientTestingModule = HttpClientTestingModule;
428 exports.TestRequest = TestRequest;
429
430 Object.defineProperty(exports, '__esModule', { value: true });
431
432}));
433//# sourceMappingURL=common-http-testing.umd.js.map