UNPKG

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