source: trip-planner-front/node_modules/@angular/common/fesm2015/http/testing.js@ ceaed42

Last change on this file since ceaed42 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

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