UNPKG

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