Quickstart
Setting up your mock
- The commonest use case is
fetchMock.mock(matcher, response)
, wherematcher
is an exact url or regex to match, andresponse
is a status code, string or object literal. - You can also use
fetchMock.once()
to limit to a single call orfetchMock.get()
,fetchMock.post()
etc. to limit to a method. - All these methods are chainable so you can easily define several mocks in a single test.
fetchMock
.get('http://good.com/', 200)
.post('http://good.com/', 400)
.get(/bad\.com/, 500);
Analysing calls to your mock
fetchMock.called(matcher)
reports if any calls matched your mock (or leavematcher
out if you just want to checkfetch
was called at all).fetchMock.lastCall()
,fetchMock.lastUrl()
orfetchMock.lastOptions()
give you access to the parameters last passed in tofetch
.fetchMock.done()
will tell you iffetch
was called the expected number of times.
Tearing down your mock
fetchMock.resetHistory()
resets the call history.fetchMock.reset()
orfetchMock.restore()
will also restorefetch()
to its native implementation
Example
Example with Node.js: suppose we have a file make-request.js
with a function that calls fetch
:
module.exports = function makeRequest() {
return fetch('http://httpbin.org/my-url', {
headers: {
user: 'me',
},
}).then(function (response) {
return response.json();
});
};
We can use fetch-mock to mock fetch
. In mocked.js
:
var makeRequest = require('./make-request');
var fetchMock = require('fetch-mock');
// Mock the fetch() global to return a response
fetchMock.get(
'http://httpbin.org/my-url',
{ hello: 'world' },
{
delay: 1000, // fake a slow network
headers: {
user: 'me', // only match requests with certain headers
},
},
);
makeRequest().then(function (data) {
console.log('got data', data);
});
// Unmock.
fetchMock.reset();
Result:
$ node mocked.js
'got data' { hello: 'world' }