testing.mjs 13 KB

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