fetch-mock

  • Version 9.11.0
  • Published
  • 3.75 MB
  • 10 dependencies
  • MIT license

Install

npm i fetch-mock
yarn add fetch-mock
pnpm add fetch-mock

Overview

Mock http requests made using fetch (or isomorphic-fetch)

Index

Variables

variable fetchMock

var fetchMock: fetchMock.FetchMockStatic;

    Interfaces

    interface FetchMockSandbox

    interface FetchMockSandbox extends FetchMockStatic {}

      call signature

      (input?: string | Request, init?: RequestInit): Promise<Response>;
      • Also callable as fetch(). Use typeof fetch in your code to define a field that accepts both fetch() and a fetch-mock sandbox.

      interface FetchMockStatic

      interface FetchMockStatic {}

        property config

        config: {
        /**
        * Convert objects into JSON before delivering as stub responses.
        * Can be useful to set to false globally if e.g. dealing with a
        * lot of array buffers. If true, will also add
        * content-type: application/json header.
        * @default true
        */
        sendAsJson?: boolean;
        /**
        * Automatically sets a content-length header on each response.
        * @default true
        */
        includeContentLength?: boolean;
        /**
        * - true: Unhandled calls fall through to the network
        * - false: Unhandled calls throw an error
        * - 'always': All calls fall through to the network, effectively
        * disabling fetch-mock.
        * @default false
        */
        fallbackToNetwork?: boolean | 'always';
        /**
        * Determines behaviour if a new route has the same name (or
        * inferred name) as an existing one
        * - undefined: An error will be throw when routes clash
        * - true: Overwrites the existing route
        * - false: Appends the new route to the list of routes
        * @default undefined
        */
        overwriteRoutes?: boolean;
        /**
        * Print a warning if any call is caught by a fallback handler (set
        * using the fallbackToNetwork option or catch())
        * @default true
        */
        warnOnFallback?: boolean;
        /**
        * Reference to the Promise constructor of a custom Promise
        * implementation.
        */
        Promise?: new (
        executor: (
        // Should be (value?: T | PromiseLike<T>) => void
        // But not sure if that's compatible with older typescript
        resolve: (value?: any) => void,
        reject: (value?: any) => void
        ) => void
        ) => Promise<any>;
        /**
        * Reference to a custom fetch implementation.
        */
        fetch?: (input?: string | Request, init?: RequestInit) => Promise<Response>;
        /**
        * Reference to the Headers constructor of a custom fetch
        * implementation.
        */
        Headers?: new () => Headers;
        /**
        * Reference to the Request constructor of a custom fetch
        * implementation.
        */
        Request?: new (input: string | Request, init?: RequestInit) => Request;
        /**
        * Reference to the Response constructor of a custom fetch
        * implementation.
        */
        Response?: new () => Response;
        };

          property MATCHED

          MATCHED: true;

            property UNMATCHED

            UNMATCHED: false;

              method called

              called: (filter?: InspectionFilter, options?: InspectionOptions) => boolean;
              • Returns a Boolean indicating whether any calls to fetch matched the given filter.

                Parameter filter

                Allows filtering of calls to fetch based on various criteria

                Parameter options

                Either an object compatible with the mocking api or a string specifying a http method to filter by. This will be used to filter the list of calls further.

              method calls

              calls: (filter?: InspectionFilter, options?: InspectionOptions) => MockCall[];
              • Returns an array of all calls to fetch matching the given filters. Each call is returned as a [url, options] array. If fetch was called using a Request instance, this will be available as a request property on this array.

                Parameter filter

                Allows filtering of calls to fetch based on various criteria

                Parameter options

                Either an object compatible with the mocking api or a string specifying a http method to filter by. This will be used to filter the list of calls further.

              method catch

              catch: (response?: MockResponse | MockResponseFunction) => this;
              • Chainable method that defines how to respond to calls to fetch that don't match any of the defined mocks. It accepts the same types of response as a normal call to .mock(matcher, response). It can also take an arbitrary function to completely customise behaviour of unmatched calls. If .catch() is called without any parameters then every unmatched call will receive a 200 response.

                Parameter response

                Configures the http response returned by the mock

              method delete

              delete: (
              matcher: MockMatcher | MockOptionsMethodDelete,
              response: MockResponse | MockResponseFunction,
              options?: MockOptionsMethodDelete
              ) => this;
              • Replaces fetch() with a stub which records its calls, grouped by route, and optionally returns a mocked Response object or passes the call through to fetch(). Shorthand for mock() restricted to the DELETE method. Calls to .delete() can be chained.

                Parameter matcher

                Condition for selecting which requests to mock

                Parameter response

                Configures the http response returned by the mock

                Parameter options

                Additional properties defining the route to mock

              method deleteOnce

              deleteOnce: (
              matcher: MockMatcher | MockOptionsMethodDelete,
              response: MockResponse | MockResponseFunction,
              options?: MockOptionsMethodDelete
              ) => this;
              • Replaces fetch() with a stub which records its calls, grouped by route, and optionally returns a mocked Response object or passes the call through to fetch(). Shorthand for mock() restricted to the DELETE method and limited to being called one time only. Calls to .deleteOnce() can be chained.

                Parameter matcher

                Condition for selecting which requests to mock

                Parameter response

                Configures the http response returned by the mock

                Parameter options

                Additional properties defining the route to mock

              method done

              done: (filter?: InspectionFilter) => boolean;
              • Returns a Boolean indicating whether fetch was called the expected number of times (or has been called at least once if repeat is undefined for the route).

                Parameter filter

                Rule for matching calls to fetch.

              method flush

              flush: (waitForBody?: boolean) => Promise<MockResponse[]>;
              • Returns a promise that resolves once all fetches handled by fetch-mock have resolved.

                Parameter waitForBody

                Wait for all body parsing methods(res.json(), res.text(), etc.) to resolve too.

              method get

              get: (
              matcher: MockMatcher | MockOptionsMethodGet,
              response: MockResponse | MockResponseFunction,
              options?: MockOptionsMethodGet
              ) => this;
              • Replaces fetch() with a stub which records its calls, grouped by route, and optionally returns a mocked Response object or passes the call through to fetch(). Shorthand for mock() restricted to the GET method. Calls to .get() can be chained.

                Parameter matcher

                Condition for selecting which requests to mock

                Parameter response

                Configures the http response returned by the mock

                Parameter options

                Additional properties defining the route to mock

              method getOnce

              getOnce: (
              matcher: MockMatcher | MockOptionsMethodGet,
              response: MockResponse | MockResponseFunction,
              options?: MockOptionsMethodGet
              ) => this;
              • Replaces fetch() with a stub which records its calls, grouped by route, and optionally returns a mocked Response object or passes the call through to fetch(). Shorthand for mock() restricted to the GET method and limited to being called one time only. Calls to .getOnce() can be chained.

                Parameter matcher

                Condition for selecting which requests to mock

                Parameter response

                Configures the http response returned by the mock

                Parameter options

                Additional properties defining the route to mock

              method head

              head: (
              matcher: MockMatcher | MockOptionsMethodHead,
              response: MockResponse | MockResponseFunction,
              options?: MockOptionsMethodHead
              ) => this;
              • Replaces fetch() with a stub which records its calls, grouped by route, and optionally returns a mocked Response object or passes the call through to fetch(). Shorthand for mock() restricted to the HEAD method. Calls to .head() can be chained.

                Parameter matcher

                Condition for selecting which requests to mock

                Parameter response

                Configures the http response returned by the mock

                Parameter options

                Additional properties defining the route to mock

              method headOnce

              headOnce: (
              matcher: MockMatcher | MockOptionsMethodHead,
              response: MockResponse | MockResponseFunction,
              options?: MockOptionsMethodHead
              ) => this;
              • Replaces fetch() with a stub which records its calls, grouped by route, and optionally returns a mocked Response object or passes the call through to fetch(). Shorthand for mock() restricted to the HEAD method and limited to being called one time only. Calls to .headOnce() can be chained.

                Parameter matcher

                Condition for selecting which requests to mock

                Parameter response

                Configures the http response returned by the mock

                Parameter options

                Additional properties defining the route to mock

              method lastCall

              lastCall: (
              filter?: InspectionFilter,
              options?: InspectionOptions
              ) => MockCall | undefined;
              • Returns the arguments for the last call to fetch matching the given filter.

                Parameter filter

                Allows filtering of calls to fetch based on various criteria

                Parameter options

                Either an object compatible with the mocking api or a string specifying a http method to filter by. This will be used to filter the list of calls further.

              method lastOptions

              lastOptions: (
              filter?: InspectionFilter,
              options?: InspectionOptions
              ) => MockOptions | undefined;
              • Returns the options for the call to fetch matching the given filter. If fetch was last called using a Request instance, a set of options inferred from the Request will be returned.

                Parameter filter

                Allows filtering of calls to fetch based on various criteria

                Parameter options

                Either an object compatible with the mocking api or a string specifying a http method to filter by. This will be used to filter the list of calls further.

              method lastResponse

              lastResponse: (
              filter?: InspectionFilter,
              options?: InspectionOptions
              ) => Response | undefined;
              • Returns the options for the call to fetch matching the given filter. This is an experimental feature, very difficult to implement well given fetch’s very private treatment of response bodies. When doing all the following: - using node-fetch - responding with a real network response (using spy() or fallbackToNetwork) - using fetchMock.LastResponse() - awaiting the body content … the response will hang unless your source code also awaits the response body. This is an unavoidable consequence of the nodejs implementation of streams.

                Parameter filter

                Allows filtering of calls to fetch based on various criteria

                Parameter options

                Either an object compatible with the mocking api or a string specifying a http method to filter by. This will be used to filter the list of calls further.

              method lastUrl

              lastUrl: (
              filter?: InspectionFilter,
              options?: InspectionOptions
              ) => string | undefined;
              • Returns the url for the last call to fetch matching the given filter. If fetch was last called using a Request instance, the url will be extracted from this.

                Parameter filter

                Allows filtering of calls to fetch based on various criteria

                Parameter options

                Either an object compatible with the mocking api or a string specifying a http method to filter by. This will be used to filter the list of calls further.

              method mock

              mock: {
              (
              matcher: MockMatcher | MockOptions,
              response: MockResponse | MockResponseFunction,
              options?: MockOptions
              ): this;
              (options: MockOptions): this;
              (): this;
              };
              • Replaces fetch() with a stub which records its calls, grouped by route, and optionally returns a mocked Response object or passes the call through to fetch(). Calls to .mock() can be chained.

                Parameter matcher

                Condition for selecting which requests to mock

                Parameter response

                Configures the http response returned by the mock

                Parameter options

                Additional properties defining the route to mock

              • Replaces fetch() with a stub which records its calls, grouped by route, and optionally returns a mocked Response object or passes the call through to fetch(). Calls to .mock() can be chained.

                Parameter options

                The route to mock

              method once

              once: (
              matcher: MockMatcher | MockOptions,
              response: MockResponse | MockResponseFunction,
              options?: MockOptions
              ) => this;
              • Replaces fetch() with a stub which records its calls, grouped by route, and optionally returns a mocked Response object or passes the call through to fetch(). Shorthand for mock() limited to being called one time only. Calls to .once() can be chained.

                Parameter matcher

                Condition for selecting which requests to mock

                Parameter response

                Configures the http response returned by the mock

                Parameter options

                Optional additional properties defining the route to mock

              method patch

              patch: (
              matcher: MockMatcher | MockOptionsMethodPatch,
              response: MockResponse | MockResponseFunction,
              options?: MockOptionsMethodPatch
              ) => this;
              • Replaces fetch() with a stub which records its calls, grouped by route, and optionally returns a mocked Response object or passes the call through to fetch(). Shorthand for mock() restricted to the PATCH method. Calls to .patch() can be chained.

                Parameter matcher

                Condition for selecting which requests to mock

                Parameter response

                Configures the http response returned by the mock

                Parameter options

                Additional properties defining the route to mock

              method patchOnce

              patchOnce: (
              matcher: MockMatcher | MockOptionsMethodPatch,
              response: MockResponse | MockResponseFunction,
              options?: MockOptionsMethodPatch
              ) => this;
              • Replaces fetch() with a stub which records its calls, grouped by route, and optionally returns a mocked Response object or passes the call through to fetch(). Shorthand for mock() restricted to the PATCH method and limited to being called one time only. Calls to .patchOnce() can be chained.

                Parameter matcher

                Condition for selecting which requests to mock

                Parameter response

                Configures the http response returned by the mock

                Parameter options

                Additional properties defining the route to mock

              method post

              post: (
              matcher: MockMatcher | MockOptionsMethodPost,
              response: MockResponse | MockResponseFunction,
              options?: MockOptionsMethodPost
              ) => this;
              • Replaces fetch() with a stub which records its calls, grouped by route, and optionally returns a mocked Response object or passes the call through to fetch(). Shorthand for mock() restricted to the POST method. Calls to .post() can be chained.

                Parameter matcher

                Condition for selecting which requests to mock

                Parameter response

                Configures the http response returned by the mock

                Parameter options

                Additional properties defining the route to mock

              method postOnce

              postOnce: (
              matcher: MockMatcher | MockOptionsMethodPost,
              response: MockResponse | MockResponseFunction,
              options?: MockOptionsMethodPost
              ) => this;
              • Replaces fetch() with a stub which records its calls, grouped by route, and optionally returns a mocked Response object or passes the call through to fetch(). Shorthand for mock() restricted to the POST method and limited to being called one time only. Calls to .postOnce() can be chained.

                Parameter matcher

                Condition for selecting which requests to mock

                Parameter response

                Configures the http response returned by the mock

                Parameter options

                Additional properties defining the route to mock

              method put

              put: (
              matcher: MockMatcher | MockOptionsMethodPut,
              response: MockResponse | MockResponseFunction,
              options?: MockOptionsMethodPut
              ) => this;
              • Replaces fetch() with a stub which records its calls, grouped by route, and optionally returns a mocked Response object or passes the call through to fetch(). Shorthand for mock() restricted to the PUT method. Calls to .put() can be chained.

                Parameter matcher

                Condition for selecting which requests to mock

                Parameter response

                Configures the http response returned by the mock

                Parameter options

                Additional properties defining the route to mock

              method putOnce

              putOnce: (
              matcher: MockMatcher | MockOptionsMethodPut,
              response: MockResponse | MockResponseFunction,
              options?: MockOptionsMethodPut
              ) => this;
              • Replaces fetch() with a stub which records its calls, grouped by route, and optionally returns a mocked Response object or passes the call through to fetch(). Shorthand for mock() restricted to the PUT method and limited to being called one time only. Calls to .putOnce() can be chained.

                Parameter matcher

                Condition for selecting which requests to mock

                Parameter response

                Configures the http response returned by the mock

                Parameter options

                Additional properties defining the route to mock

              method reset

              reset: () => this;
              • Restores fetch() to its unstubbed state and clears all data recorded for its calls. reset() is an alias for restore().

              method resetBehavior

              resetBehavior: () => this;
              • Removes mocking behaviour without resetting call history.

              method resetHistory

              resetHistory: () => this;
              • Clears all data recorded for fetch()’s calls. It will not restore fetch to its default implementation.

              method restore

              restore: () => this;
              • Restores fetch() to its unstubbed state and clears all data recorded for its calls. reset() is an alias for restore().

              method sandbox

              sandbox: () => FetchMockSandbox;
              • Returns a drop-in mock for fetch which can be passed to other mocking libraries. It implements the full fetch-mock api and maintains its own state independent of other instances, so tests can be run in parallel.

              method spy

              spy: (response?: MockResponse | MockResponseFunction) => this;
              • Chainable method that records the call history of unmatched calls, but instead of responding with a stubbed response, the request is passed through to native fetch() and is allowed to communicate over the network. Similar to catch().

              interface MockCall

              interface MockCall extends Array<string | RequestInit | undefined> {}

                property 0

                0: string;

                  property 1

                  1: RequestInit | undefined;

                    property identifier

                    identifier: string;

                      property isUnmatched

                      isUnmatched: boolean | undefined;

                        property request

                        request: Request | undefined;

                          property response

                          response: Response | undefined;

                            interface MockOptions

                            interface MockOptions {}
                            • Mock options object

                            property body

                            body?: object;
                            • JSON serialisable object literal. Allowing any object for now But in typescript 3.7 will change to JSON

                            property delay

                            delay?: number;
                            • integer, n, delays responding for the number of milliseconds specified.

                            property functionMatcher

                            functionMatcher?: MockMatcherFunction;
                            • A function for arbitrary matching

                            property headers

                            headers?: { [key: string]: string | number };
                            • key/value map of headers to match

                            property includeContentLength

                            includeContentLength?: boolean;
                            • Automatically sets a content-length header on each response. true

                            property matcher

                            matcher?: MockMatcher;
                            • as specified above

                            property matchPartialBody

                            matchPartialBody?: boolean;
                            • Match calls that only partially match a specified body json.

                            property method

                            method?: string;
                            • http method to match

                            property name

                            name?: string;
                            • A unique string naming the route. Used to subsequently retrieve references to the calls, grouped by name. matcher.toString()

                              Note: If a non-unique name is provided no error will be thrown (because names are optional, auto-generated ones may legitimately clash)

                            property overwriteRoutes

                            overwriteRoutes?: boolean;
                            • This option allows for existing routes in a mock to be overwritten. It’s also possible to define multiple routes with ‘the same’ matcher. Default behaviour is to error

                            property params

                            params?: { [key: string]: string };
                            • key/value map of express style path params to match

                            property query

                            query?: object;
                            • key/value map of query strings to match, in any order

                            property repeat

                            repeat?: number;
                            • integer, n, limiting the number of times the matcher can be used. If the route has already been called n times the route will be ignored and the call to fetch() will fall through to be handled by any other routes defined (which may eventually result in an error if nothing matches it).

                            property response

                            response?: MockResponse | MockResponseFunction;
                            • as specified above

                            property sendAsJson

                            sendAsJson?: boolean;
                            • Convert objects into JSON before delivering as stub responses. Can be useful to set to false globally if e.g. dealing with a lot of array buffers. If true, will also add content-type: application/json header. true

                            property url

                            url?: MockMatcherUrl;

                              interface MockOptionsMethodDelete

                              interface MockOptionsMethodDelete extends MockOptions {}

                                property method

                                method?: 'DELETE';

                                  interface MockOptionsMethodGet

                                  interface MockOptionsMethodGet extends MockOptions {}

                                    property method

                                    method?: 'GET';

                                      interface MockOptionsMethodHead

                                      interface MockOptionsMethodHead extends MockOptions {}

                                        property method

                                        method?: 'HEAD';

                                          interface MockOptionsMethodPatch

                                          interface MockOptionsMethodPatch extends MockOptions {}

                                            property method

                                            method?: 'PATCH';

                                              interface MockOptionsMethodPost

                                              interface MockOptionsMethodPost extends MockOptions {}

                                                property method

                                                method?: 'POST';

                                                  interface MockOptionsMethodPut

                                                  interface MockOptionsMethodPut extends MockOptions {}

                                                    property method

                                                    method?: 'PUT';

                                                      interface MockResponseObject

                                                      interface MockResponseObject {}
                                                      • Mock response object

                                                      property body

                                                      body?: string | {};
                                                      • Set the response body

                                                      property headers

                                                      headers?: { [key: string]: string };
                                                      • Set the response headers.

                                                      property redirectUrl

                                                      redirectUrl?: string;
                                                      • The URL the response should be from (to imitate followed redirects - will set redirected: true on the response)

                                                      property status

                                                      status?: number;
                                                      • Set the response status 200

                                                      property throws

                                                      throws?: Error;
                                                      • If this property is present then a Promise rejected with the value of throws is returned

                                                      Type Aliases

                                                      type InspectionFilter

                                                      type InspectionFilter = MockMatcher | boolean;
                                                      • Inspection filter. Can be one of the following: boolean: * true retrieves all calls matched by fetch. fetchMock.MATCHED is an alias for true and may be used to make tests more readable. * false retrieves all calls not matched by fetch (i.e. those handled by catch() or spy(). fetchMock.UNMATCHED is an alias for false and may be used to make tests more readable. MockMatcher (routeIdentifier): All routes have an identifier: * If it’s a named route, the identifier is the route’s name * If the route is unnamed, the identifier is the matcher passed in to .mock() All calls that were handled by the route with the given identifier will be retrieved MockMatcher (matcher): Any matcher compatible with the mocking api can be passed in to filter the calls arbitrarily.

                                                      type InspectionOptions

                                                      type InspectionOptions = MockOptions | string;
                                                      • Either an object compatible with the mocking api or a string specifying a http method to filter by. This will be used to filter the list of calls further.

                                                      type MockMatcher

                                                      type MockMatcher = MockMatcherUrl | MockMatcherFunction;
                                                      • Mock matcher. Can be one of following: string: Either * an exact url to match e.g. 'http://www.site.com/page.html' * if the string begins with a ^, the string following the ^ must begin the url e.g. '^http://www.site.com' would match 'http://www.site.com' or 'http://www.site.com/page.html' * '*' to match any url RegExp: A regular expression to test the url against Function(url, opts): A function (returning a Boolean) that is passed the url and opts fetch() is called with (or, if fetch() was called with one, the Request instance)

                                                      type MockMatcherFunction

                                                      type MockMatcherFunction = (url: string, opts: MockRequest) => boolean;
                                                      • Mock matcher function

                                                      type MockMatcherUrl

                                                      type MockMatcherUrl = string | RegExp;

                                                        type MockRequest

                                                        type MockRequest = Request | RequestInit;

                                                          type MockResponse

                                                          type MockResponse =
                                                          | Response
                                                          | Promise<Response>
                                                          | number
                                                          | Promise<number>
                                                          | string
                                                          | Promise<string>
                                                          | {}
                                                          | Promise<{}>
                                                          | MockResponseObject
                                                          | Promise<MockResponseObject>;
                                                          • Response: A Response instance - will be used unaltered number: Creates a response with this status string: Creates a 200 response with the string as the response body object: As long as the object is not a MockResponseObject it is converted into a json string and returned as the body of a 200 response If MockResponseObject was given then it's used to configure response Function(url, opts): A function that is passed the url and opts fetch() is called with and that returns any of the responses listed above

                                                          type MockResponseFunction

                                                          type MockResponseFunction = (url: string, opts: MockRequest) => MockResponse;
                                                          • Mock response function

                                                          Package Files (1)

                                                          Dependencies (10)

                                                          Dev Dependencies (36)

                                                          Peer Dependencies (1)

                                                          Badge

                                                          To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                          You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/fetch-mock.

                                                          • Markdown
                                                            [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/fetch-mock)
                                                          • HTML
                                                            <a href="https://www.jsdocs.io/package/fetch-mock"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>