testing.mjs 13 KB

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