UNPKG

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