UNPKG

26.9 kBTypeScriptView Raw
1declare namespace fetchMock {
2 type MockRequest = Request | RequestInit;
3
4 /**
5 * Mock matcher function
6 */
7 type MockMatcherFunction = (url: string, opts: MockRequest) => boolean;
8
9 /**
10 * Mock matcher. Can be one of following:
11 * string: Either
12 * * an exact url to match e.g. 'http://www.site.com/page.html'
13 * * if the string begins with a `^`, the string following the `^` must
14 * begin the url e.g. '^http://www.site.com' would match
15 * 'http://www.site.com' or 'http://www.site.com/page.html'
16 * * '*' to match any url
17 * RegExp: A regular expression to test the url against
18 * Function(url, opts): A function (returning a Boolean) that is passed the
19 * url and opts fetch() is called with (or, if fetch() was called with one,
20 * the Request instance)
21 */
22 type MockMatcher = string | RegExp | MockMatcherFunction;
23
24 /**
25 * Inspection filter. Can be one of the following:
26 * boolean:
27 * * true retrieves all calls matched by fetch.
28 * fetchMock.MATCHED is an alias for true and may be used to make tests
29 * more readable.
30 * * false retrieves all calls not matched by fetch (i.e. those handled
31 * by catch() or spy(). fetchMock.UNMATCHED is an alias for false and
32 * may be used to make tests more readable.
33 * MockMatcher (routeIdentifier):
34 * All routes have an identifier:
35 * * If it’s a named route, the identifier is the route’s name
36 * * If the route is unnamed, the identifier is the matcher passed in to
37 * .mock()
38 * All calls that were handled by the route with the given identifier
39 * will be retrieved
40 * MockMatcher (matcher):
41 * Any matcher compatible with the mocking api can be passed in to filter
42 * the calls arbitrarily.
43 */
44 type InspectionFilter = MockMatcher | boolean;
45
46 /**
47 * Either an object compatible with the mocking api or a string specifying
48 * a http method to filter by. This will be used to filter the list of
49 * calls further.
50 */
51 type InspectionOptions = MockOptions | string;
52
53 /**
54 * Mock response object
55 */
56 interface MockResponseObject {
57 /**
58 * Set the response body
59 */
60 body?: string | {} | undefined;
61
62 /**
63 * Set the response status
64 * @default 200
65 */
66 status?: number | undefined;
67
68 /**
69 * Set the response headers.
70 */
71 headers?: { [key: string]: string } | undefined;
72
73 /**
74 * If this property is present then a Promise rejected with the value
75 * of throws is returned
76 */
77 throws?: Error | undefined;
78
79 /**
80 * The URL the response should be from (to imitate followed redirects
81 * - will set redirected: true on the response)
82 */
83 redirectUrl?: string | undefined;
84 }
85
86 /**
87 * Response: A Response instance - will be used unaltered
88 * number: Creates a response with this status
89 * string: Creates a 200 response with the string as the response body
90 * object: As long as the object is not a MockResponseObject it is
91 * converted into a json string and returned as the body of a 200 response
92 * If MockResponseObject was given then it's used to configure response
93 * Function(url, opts): A function that is passed the url and opts fetch()
94 * is called with and that returns any of the responses listed above
95 */
96 type MockResponse =
97 | Response
98 | Promise<Response>
99 | number
100 | Promise<number>
101 | string
102 | Promise<string>
103 | {}
104 | Promise<{}>
105 | MockResponseObject
106 | Promise<MockResponseObject>;
107
108 /**
109 * Mock response function
110 */
111 type MockResponseFunction = (url: string, opts: MockRequest) => MockResponse;
112
113 /**
114 * Mock options object
115 */
116 interface MockOptions {
117 /**
118 * A unique string naming the route. Used to subsequently retrieve
119 * references to the calls, grouped by name.
120 * @default matcher.toString()
121 *
122 * Note: If a non-unique name is provided no error will be thrown
123 * (because names are optional, auto-generated ones may legitimately
124 * clash)
125 */
126 name?: string | undefined;
127
128 /**
129 * http method to match
130 */
131 method?: string | undefined;
132
133 /**
134 * key/value map of headers to match
135 */
136 headers?: { [key: string]: string | number } | undefined;
137
138 /**
139 * body to match
140 */
141 body?: string | {} | undefined;
142
143 /**
144 * key/value map of query strings to match, in any order
145 */
146 query?: { [key: string]: string } | undefined;
147
148 /**
149 * key/value map of express style path params to match
150 */
151 params?: { [key: string]: string } | undefined;
152
153 /**
154 * A function for arbitrary matching
155 */
156 functionMatcher?: MockMatcherFunction | undefined;
157
158 /**
159 * as specified above
160 */
161 matcher?: MockMatcher | undefined;
162
163 /**
164 * This option allows for existing routes in a mock to be overwritten.
165 * It’s also possible to define multiple routes with ‘the same’ matcher.
166 * Default behaviour is to error
167 */
168 overwriteRoutes?: boolean | undefined;
169
170 /**
171 * as specified above
172 */
173 response?: MockResponse | MockResponseFunction | undefined;
174
175 /**
176 * integer, n, limiting the number of times the matcher can be used.
177 * If the route has already been called n times the route will be
178 * ignored and the call to fetch() will fall through to be handled by
179 * any other routes defined (which may eventually result in an error
180 * if nothing matches it).
181 */
182 repeat?: number | undefined;
183
184 /**
185 * Convert objects into JSON before delivering as stub responses. Can
186 * be useful to set to false globally if e.g. dealing with a lot of
187 * array buffers. If true, will also add content-type: application/json
188 * header.
189 * @default true
190 */
191 sendAsJson?: boolean | undefined;
192
193 /**
194 * Automatically sets a content-length header on each response.
195 * @default true
196 */
197 includeContentLength?: boolean | undefined;
198 }
199
200 interface MockCall extends Array<string | RequestInit | undefined> {
201 0: string;
202 1: RequestInit | undefined;
203 identifier: string;
204 isUnmatched: boolean | undefined;
205 request: Request | undefined;
206 }
207
208 interface MockOptionsMethodGet extends MockOptions {
209 method?: "GET" | undefined;
210 }
211
212 interface MockOptionsMethodPost extends MockOptions {
213 method?: "POST" | undefined;
214 }
215
216 interface MockOptionsMethodPut extends MockOptions {
217 method?: "PUT" | undefined;
218 }
219
220 interface MockOptionsMethodDelete extends MockOptions {
221 method?: "DELETE" | undefined;
222 }
223
224 interface MockOptionsMethodHead extends MockOptions {
225 method?: "HEAD" | undefined;
226 }
227
228 interface FetchMockStatic {
229 MATCHED: true;
230 UNMATCHED: false;
231
232 /**
233 * Replaces fetch() with a stub which records its calls, grouped by
234 * route, and optionally returns a mocked Response object or passes the
235 * call through to fetch(). Calls to .mock() can be chained.
236 * @param matcher Condition for selecting which requests to mock
237 * @param response Configures the http response returned by the mock
238 * @param [options] Additional properties defining the route to mock
239 */
240 mock(matcher: MockMatcher, response: MockResponse | MockResponseFunction, options?: MockOptions): this;
241
242 /**
243 * Replaces fetch() with a stub which records its calls, grouped by
244 * route, and optionally returns a mocked Response object or passes the
245 * call through to fetch(). Calls to .mock() can be chained.
246 * @param options The route to mock
247 */
248 mock(options: MockOptions): this;
249
250 /**
251 * Returns a drop-in mock for fetch which can be passed to other mocking
252 * libraries. It implements the full fetch-mock api and maintains its
253 * own state independent of other instances, so tests can be run in
254 * parallel.
255 */
256 sandbox(): FetchMockSandbox;
257
258 /**
259 * Replaces fetch() with a stub which records its calls, grouped by
260 * route, and optionally returns a mocked Response object or passes the
261 * call through to fetch(). Shorthand for mock() limited to being
262 * called one time only. Calls to .once() can be chained.
263 * @param matcher Condition for selecting which requests to mock
264 * @param response Configures the http response returned by the mock
265 * @param [options] Optional additional properties defining the route to mock
266 */
267 once(matcher: MockMatcher, response: MockResponse | MockResponseFunction, options?: MockOptions): this;
268
269 /**
270 * Replaces fetch() with a stub which records its calls, grouped by
271 * route, and optionally returns a mocked Response object or passes the
272 * call through to fetch(). Shorthand for mock() restricted to the GET
273 * method. Calls to .get() can be chained.
274 * @param matcher Condition for selecting which requests to mock
275 * @param response Configures the http response returned by the mock
276 * @param [options] Additional properties defining the route to mock
277 */
278 get(matcher: MockMatcher, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodGet): this;
279
280 /**
281 * Replaces fetch() with a stub which records its calls, grouped by
282 * route, and optionally returns a mocked Response object or passes the
283 * call through to fetch(). Shorthand for mock() restricted to the GET
284 * method and limited to being called one time only. Calls to .getOnce()
285 * can be chained.
286 * @param matcher Condition for selecting which requests to mock
287 * @param response Configures the http response returned by the mock
288 * @param [options] Additional properties defining the route to mock
289 */
290 getOnce(
291 matcher: MockMatcher,
292 response: MockResponse | MockResponseFunction,
293 options?: MockOptionsMethodGet,
294 ): this;
295
296 /**
297 * Replaces fetch() with a stub which records its calls, grouped by
298 * route, and optionally returns a mocked Response object or passes the
299 * call through to fetch(). Shorthand for mock() restricted to the POST
300 * method. Calls to .post() can be chained.
301 * @param matcher Condition for selecting which requests to mock
302 * @param response Configures the http response returned by the mock
303 * @param [options] Additional properties defining the route to mock
304 */
305 post(
306 matcher: MockMatcher,
307 response: MockResponse | MockResponseFunction,
308 options?: MockOptionsMethodPost,
309 ): this;
310
311 /**
312 * Replaces fetch() with a stub which records its calls, grouped by
313 * route, and optionally returns a mocked Response object or passes the
314 * call through to fetch(). Shorthand for mock() restricted to the POST
315 * method and limited to being called one time only. Calls to .postOnce()
316 * can be chained.
317 * @param matcher Condition for selecting which requests to mock
318 * @param response Configures the http response returned by the mock
319 * @param [options] Additional properties defining the route to mock
320 */
321 postOnce(
322 matcher: MockMatcher,
323 response: MockResponse | MockResponseFunction,
324 options?: MockOptionsMethodPost,
325 ): this;
326
327 /**
328 * Replaces fetch() with a stub which records its calls, grouped by
329 * route, and optionally returns a mocked Response object or passes the
330 * call through to fetch(). Shorthand for mock() restricted to the PUT
331 * method. Calls to .put() can be chained.
332 * @param matcher Condition for selecting which requests to mock
333 * @param response Configures the http response returned by the mock
334 * @param [options] Additional properties defining the route to mock
335 */
336 put(matcher: MockMatcher, response: MockResponse | MockResponseFunction, options?: MockOptionsMethodPut): this;
337
338 /**
339 * Replaces fetch() with a stub which records its calls, grouped by
340 * route, and optionally returns a mocked Response object or passes the
341 * call through to fetch(). Shorthand for mock() restricted to the PUT
342 * method and limited to being called one time only. Calls to .putOnce()
343 * can be chained.
344 * @param matcher Condition for selecting which requests to mock
345 * @param response Configures the http response returned by the mock
346 * @param [options] Additional properties defining the route to mock
347 */
348 putOnce(
349 matcher: MockMatcher,
350 response: MockResponse | MockResponseFunction,
351 options?: MockOptionsMethodPut,
352 ): this;
353
354 /**
355 * Replaces fetch() with a stub which records its calls, grouped by
356 * route, and optionally returns a mocked Response object or passes the
357 * call through to fetch(). Shorthand for mock() restricted to the
358 * DELETE method. Calls to .delete() can be chained.
359 * @param matcher Condition for selecting which requests to mock
360 * @param response Configures the http response returned by the mock
361 * @param [options] Additional properties defining the route to mock
362 */
363 delete(
364 matcher: MockMatcher,
365 response: MockResponse | MockResponseFunction,
366 options?: MockOptionsMethodDelete,
367 ): this;
368
369 /**
370 * Replaces fetch() with a stub which records its calls, grouped by
371 * route, and optionally returns a mocked Response object or passes the
372 * call through to fetch(). Shorthand for mock() restricted to the
373 * DELETE method and limited to being called one time only. Calls to
374 * .deleteOnce() can be chained.
375 * @param matcher Condition for selecting which requests to mock
376 * @param response Configures the http response returned by the mock
377 * @param [options] Additional properties defining the route to mock
378 */
379 deleteOnce(
380 matcher: MockMatcher,
381 response: MockResponse | MockResponseFunction,
382 options?: MockOptionsMethodDelete,
383 ): this;
384
385 /**
386 * Replaces fetch() with a stub which records its calls, grouped by
387 * route, and optionally returns a mocked Response object or passes the
388 * call through to fetch(). Shorthand for mock() restricted to the HEAD
389 * method. Calls to .head() can be chained.
390 * @param matcher Condition for selecting which requests to mock
391 * @param response Configures the http response returned by the mock
392 * @param [options] Additional properties defining the route to mock
393 */
394 head(
395 matcher: MockMatcher,
396 response: MockResponse | MockResponseFunction,
397 options?: MockOptionsMethodHead,
398 ): this;
399
400 /**
401 * Replaces fetch() with a stub which records its calls, grouped by
402 * route, and optionally returns a mocked Response object or passes the
403 * call through to fetch(). Shorthand for mock() restricted to the HEAD
404 * method and limited to being called one time only. Calls to .headOnce()
405 * can be chained.
406 * @param matcher Condition for selecting which requests to mock
407 * @param response Configures the http response returned by the mock
408 * @param [options] Additional properties defining the route to mock
409 */
410 headOnce(
411 matcher: MockMatcher,
412 response: MockResponse | MockResponseFunction,
413 options?: MockOptionsMethodHead,
414 ): this;
415
416 /**
417 * Replaces fetch() with a stub which records its calls, grouped by
418 * route, and optionally returns a mocked Response object or passes the
419 * call through to fetch(). Shorthand for mock() restricted to the PATCH
420 * method. Calls to .patch() can be chained.
421 * @param matcher Condition for selecting which requests to mock
422 * @param response Configures the http response returned by the mock
423 * @param [options] Additional properties defining the route to mock
424 */
425 patch(
426 matcher: MockMatcher,
427 response: MockResponse | MockResponseFunction,
428 options?: MockOptionsMethodHead,
429 ): this;
430
431 /**
432 * Replaces fetch() with a stub which records its calls, grouped by
433 * route, and optionally returns a mocked Response object or passes the
434 * call through to fetch(). Shorthand for mock() restricted to the PATCH
435 * method and limited to being called one time only. Calls to .patchOnce()
436 * can be chained.
437 * @param matcher Condition for selecting which requests to mock
438 * @param response Configures the http response returned by the mock
439 * @param [options] Additional properties defining the route to mock
440 */
441 patchOnce(
442 matcher: MockMatcher,
443 response: MockResponse | MockResponseFunction,
444 options?: MockOptionsMethodHead,
445 ): this;
446
447 /**
448 * Chainable method that defines how to respond to calls to fetch that
449 * don't match any of the defined mocks. It accepts the same types of
450 * response as a normal call to .mock(matcher, response). It can also
451 * take an arbitrary function to completely customise behaviour of
452 * unmatched calls. If .catch() is called without any parameters then
453 * every unmatched call will receive a 200 response.
454 * @param [response] Configures the http response returned by the mock
455 */
456 catch(response?: MockResponse | MockResponseFunction): this;
457
458 /**
459 * Chainable method that records the call history of unmatched calls,
460 * but instead of responding with a stubbed response, the request is
461 * passed through to native fetch() and is allowed to communicate
462 * over the network. Similar to catch().
463 */
464 spy(response?: MockResponse | MockResponseFunction): this;
465
466 /**
467 * Restores fetch() to its unstubbed state and clears all data recorded
468 * for its calls. reset() is an alias for restore().
469 */
470 restore(): this;
471
472 /**
473 * Restores fetch() to its unstubbed state and clears all data recorded
474 * for its calls. reset() is an alias for restore().
475 */
476 reset(): this;
477
478 /**
479 * Clears all data recorded for fetch()’s calls. It will not restore
480 * fetch to its default implementation.
481 */
482 resetHistory(): this;
483
484 /**
485 * Removes mocking behaviour without resetting call history.
486 */
487 resetBehavior(): this;
488
489 /**
490 * Returns a promise that resolves once all fetches handled by fetch-mock
491 * have resolved.
492 * @param [waitForBody] Wait for all body parsing methods(res.json(),
493 * res.text(), etc.) to resolve too.
494 */
495 flush(waitForBody?: boolean): Promise<MockResponse[]>;
496
497 /**
498 * Returns an array of all calls to fetch matching the given filters.
499 * Each call is returned as a [url, options] array. If fetch was called
500 * using a Request instance, this will be available as a request
501 * property on this array.
502 * @param [filter] Allows filtering of calls to fetch based on various
503 * criteria
504 * @param [options] Either an object compatible with the mocking api or
505 * a string specifying a http method to filter by. This will be used to
506 * filter the list of calls further.
507 */
508 calls(filter?: InspectionFilter, options?: InspectionOptions): MockCall[];
509
510 /**
511 * Returns a Boolean indicating whether any calls to fetch matched the
512 * given filter.
513 * @param [filter] Allows filtering of calls to fetch based on various
514 * criteria
515 * @param [options] Either an object compatible with the mocking api or
516 * a string specifying a http method to filter by. This will be used to
517 * filter the list of calls further.
518 */
519 called(filter?: InspectionFilter, options?: InspectionOptions): boolean;
520
521 /**
522 * Returns a Boolean indicating whether fetch was called the expected
523 * number of times (or has been called at least once if repeat is
524 * undefined for the route).
525 * @param [filter] Rule for matching calls to fetch.
526 */
527 done(filter?: InspectionFilter): boolean;
528
529 /**
530 * Returns the arguments for the last call to fetch matching the given
531 * filter.
532 * @param [filter] Allows filtering of calls to fetch based on various
533 * criteria
534 * @param [options] Either an object compatible with the mocking api or
535 * a string specifying a http method to filter by. This will be used to
536 * filter the list of calls further.
537 */
538 lastCall(
539 filter?: InspectionFilter,
540 options?: InspectionOptions,
541 ): MockCall | undefined;
542
543 /**
544 * Returns the url for the last call to fetch matching the given
545 * filter. If fetch was last called using a Request instance, the url
546 * will be extracted from this.
547 * @param [filter] Allows filtering of calls to fetch based on various
548 * criteria
549 * @param [options] Either an object compatible with the mocking api or
550 * a string specifying a http method to filter by. This will be used to
551 * filter the list of calls further.
552 */
553 lastUrl(
554 filter?: InspectionFilter,
555 options?: InspectionOptions,
556 ): string | undefined;
557
558 /**
559 * Returns the options for the call to fetch matching the given filter.
560 * If fetch was last called using a Request instance, a set of options
561 * inferred from the Request will be returned.
562 * @param [filter] Allows filtering of calls to fetch based on various
563 * criteria
564 * @param [options] Either an object compatible with the mocking api or
565 * a string specifying a http method to filter by. This will be used to
566 * filter the list of calls further.
567 */
568 lastOptions(
569 filter?: InspectionFilter,
570 options?: InspectionOptions,
571 ): MockOptions | undefined;
572
573 config: {
574 /**
575 * Convert objects into JSON before delivering as stub responses.
576 * Can be useful to set to false globally if e.g. dealing with a
577 * lot of array buffers. If true, will also add
578 * content-type: application/json header.
579 * @default true
580 */
581 sendAsJson?: boolean | undefined;
582
583 /**
584 * Automatically sets a content-length header on each response.
585 * @default true
586 */
587 includeContentLength?: boolean | undefined;
588
589 /**
590 * - true: Unhandled calls fall through to the network
591 * - false: Unhandled calls throw an error
592 * - 'always': All calls fall through to the network, effectively
593 * disabling fetch-mock.
594 * @default false
595 */
596 fallbackToNetwork?: boolean | "always" | undefined;
597
598 /**
599 * Determines behaviour if a new route has the same name (or
600 * inferred name) as an existing one
601 * - undefined: An error will be throw when routes clash
602 * - true: Overwrites the existing route
603 * - false: Appends the new route to the list of routes
604 * @default undefined
605 */
606 overwriteRoutes?: boolean | undefined;
607
608 /**
609 * Print a warning if any call is caught by a fallback handler (set
610 * using the fallbackToNetwork option or catch())
611 * @default true
612 */
613 warnOnFallback?: boolean | undefined;
614
615 /**
616 * Reference to the Promise constructor of a custom Promise
617 * implementation.
618 */
619 Promise?: new(
620 executor: (
621 resolve: (value: Response | PromiseLike<Response>) => void,
622 reject: (reason?: any) => void,
623 ) => void,
624 ) => Promise<Response> | undefined | undefined;
625
626 /**
627 * Reference to a custom fetch implementation.
628 */
629 fetch?:
630 | ((
631 input?: string | Request,
632 init?: RequestInit,
633 ) => Promise<Response>)
634 | undefined;
635
636 /**
637 * Reference to the Headers constructor of a custom fetch
638 * implementation.
639 */
640 Headers?: (new() => Headers | undefined) | undefined;
641
642 /**
643 * Reference to the Request constructor of a custom fetch
644 * implementation.
645 */
646 Request?: (new(input: string | Request, init?: RequestInit) => Request | undefined) | undefined;
647
648 /**
649 * Reference to the Response constructor of a custom fetch
650 * implementation.
651 */
652 Response?: (new() => Response | undefined) | undefined;
653 };
654 }
655
656 interface FetchMockSandbox extends FetchMockStatic {
657 /**
658 * Also callable as fetch(). Use `typeof fetch` in your code to define
659 * a field that accepts both `fetch()` and a fetch-mock sandbox.
660 */
661 (input?: string | Request, init?: RequestInit): Promise<Response>;
662 }
663}
664
665declare var fetchMock: fetchMock.FetchMockStatic;
666export = fetchMock;
667
\No newline at end of file