- Introduction
- Quickstart
- Installation and usage
- API documentation
- Troubleshooting
- Examples
API Documentation
Mocking calls to fetch
mock(matcher, response, options) or mock(options)
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. Note that once mocked, fetch will error on any unmatched calls. Use .spy() or .catch() to handle unmocked calls more gracefully
matcher: Condition for selecting which requests to mock. (For matching based on headers, query strings or otherfetchoptions see theoptionsparameter documented below). Accepts any of the following:string: Either- an exact url to match e.g. ‘http://www.site.com/page.html’
*to match any urlbegin:http://www.site.com/to match urls beginning with a stringend:.jpgto match urls ending with a stringglob:http://*.*to match glob patternsexpress:/user/:userto match express style paths
RegExp: A regular expression to test the url againstFunction(url, opts): A function (returning a Boolean) that is passed the url and optsfetch()is called with (or, iffetch()was called with one, theRequestinstance)
response: Configures the http response returned by the mock. Can take any of the following values (or be aPromisefor any of them, enabling full control when testing race conditions etc.)Response: AResponseinstance - will be used unalterednumber: Creates a response with this statusstring: Creates a 200 response with the string as the response bodyconfigObjectIf an object does not contain any properties aside from those listed below it is treated as config to build aResponsebody: Set the response body (stringorobject)status: Set the response status (default200)headers: Set the response headers. (object)throws: If this property is present then a the value ofthrowsis thrownsendAsJson: This property determines whether or not the request body should be converted toJSONbefore being sent (defaults totrue).includeContentLength: Set this property to true to automatically add thecontent-lengthheader (defaults totrue).redirectUrl: experimental the url the response should be from (to imitate followed redirects - will setredirected: trueon the response)
object: All objects that do not meet the criteria above are converted toJSONand returned as the body of a 200 response.Function(url, opts): A function that is passed the url and optsfetch()is called with and that returns any of the responses listed above (or aPromisefor any of them)
options: A configuration object with all/additional properties to define a route to mockname: A unique string naming the route. Used to subsequently retrieve references to the calls, grouped by name. Defaults tomatcher.toString()method: http method to matchheaders: key/value map of headers to matchquery: key/value map of query strings to match, in any ordermatcher: as specified aboveresponse: as specified aboverepeat: An integer,n, limiting the number of times the matcher can be used. If the route has already been calledntimes the route will be ignored and the call tofetch()will fall through to be handled by any other routes defined (which may eventually result in an error if nothing matches it)overwriteRoutes: If the route you’re adding clashes with an existing route, settingtruehere will overwrite the clashing route,falsewill add another route to the stack which will be used as a fallback (useful when using therepeatoption). Adding a clashing route without specifying this option will throw an error. It can also be set as a global option (see the Config section below)
sandbox()
This 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. e.g.
once()
Shorthand for mock() which limits to being called one time only. (see repeat option above)
get(), post(), put(), delete(), head(), patch()
Shorthands for mock() restricted to a particular method Tip: if you use some other method a lot you can easily define your own shorthands e.g.:
fetchMock.purge = function (matcher, response, options) {
return this.mock(matcher, response, Object.assign({}, options, {method: 'PURGE'}));
}
getOnce(), postOnce(), putOnce(), deleteOnce(), headOnce(), patchOnce()
Shorthands for mock() restricted to a particular method and that will only respond once
catch(response)
This is used to define 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(). It can also take an arbitrary function to completely customise behaviour of unmatched calls. It is chainable and can be called before or after other calls to .mock(). If .catch() is called without any parameters then every unmatched call will receive a 200 response
spy()
Similar to catch(), this 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.
To use .spy() on a sandboxed fetchMock, fetchMock.config.fetch must be set to a reference to the fetch implementation you use in your code.
fetchMock.sandbox().mock('http://domain.com', 200)
Existing sandboxed fetchMocks can also have .sandbox() called on them, thus building mocks that inherit some settings from a parent mock
restore()
Chainable method that restores fetch() to its unstubbed state and clears all data recorded for its calls.
reset()
Chainable method that clears all data recorded for fetch()’s calls. It will not restore fetch to its default implementation
Note that restore() and reset() are both bound to fetchMock, and can be used directly as callbacks e.g. afterEach(fetchMock.restore) will work just fine. There is no need for afterEach(function () {fetchMock.restore()})
Inspecting how fetch() has been called
Filtering
Most of the methods below accept two parameters, (filter, method)
filterEnables filtering fetch calls for the most commonly use cases. It can be:- the name of a route
- The value of
matcherormatcher.toString()for any unnamed route. You can pass in the original regex or function as a matcher, but they will be converted to strings and used to look up values in fetch-mock’s internal maps of calls, not used as regexes or functions executed on teh url - If
filteris a string, and it does not match any routes, it is asumed the string is a url, and calls tofetchmade with that url are returned truefor matched calls onlyfalsefor unmatched calls onlyundefinedfor all calls to fetch
methodA http method to filter by
called(filter, method)
Returns a Boolean indicating whether fetch was called and a route was matched. If filter is specified it only returns true if that particular route was matched.
done(filter, method)
Returns a Boolean indicating whether fetch was called the expected number of times (or at least once if the route defines no expectation is set for the route). Unlike the other methods for inspecting calls, unmatched calls are irrelevant. Therefore, if no filter is passed, done() returns true if every route has been called the number of expected times.
calls(filter, method)
Returns an array of all calls to fetch matchingthe given filters. Each call is returned as an array of length 2.
lastCall(filter, method)
Returns the arguments for the last matched call to fetch
lastUrl(filter, method)
Returns the url for the last matched call to fetch. When fetch was last called using a Request instance, the url will be extracted from this
lastOptions(filter, method)
Returns the options for the last matched call to fetch. When fetch was last called using a Request instance, the entire Request instance will be returned
flush()
Returns a Promise that resolves once all fetches handled by fetch-mock have resolved. Useful for testing code that uses fetch but doesn’t return a promise.
Config
On either the global or sandboxed fetchMock instances, the following config options can be set by setting properties on fetchMock.config. Many can also be set on individual calls to .mock().
sendAsJson[defaulttrue] - by default fetchMock will convert objects to JSON before sending. This is overrideable from each call but for some scenarios e.g. when dealing with a lot of array buffers, it can be useful to default tofalseincludeContentLength[defaulttrue]: When set to true this will make fetchMock automatically add thecontent-lengthheader. This is especially useful when combined withsendAsJsonbecause then fetchMock does the conversion to JSON for you and knows the resulting length so you don’t have to compute this yourself by basically doing the same conversion to JSON.fallbackToNetwork[defaultfalse] If true then unmatched calls will transparently fall through to the network, if false an error will be thrown. Within individual tests.catch()andspy()can be used for fine-grained control of thisoverwriteRoutes: If a new route clashes with an existing route, settingtruehere will overwrite the clashing route,falsewill add another route to the stack which will be used as a fallback (useful when using therepeatoption). Adding a clashing route without specifying this option will throw an error.warnOnFallback[defaulttrue] If true then any unmatched calls that are caught by a fallback handler (either the network or a custom function set usingcatch()) will emit warningsHeaders,Request,Response,Promise,fetchWhen using non standard fetch (e.g. a ponyfill, or aversion ofnode-fetchother than the one bundled withfetch-mock) or an alternative Promise implementation, this will configure fetch-mock to use your chosen implementations.
Note that Object.assign(fetchMock.config, require('fetch-ponyfill')()) will configure fetch-mock to use all of fetch-ponyfill’s classes. In most cases, it should only be necessary to set this once before any tests run.