testing.mjs 13 KB

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