Fetch is the canonical way to do HTTP requests in the browser, and it can be used in other environments such as React Native. Jest Fetch Mock allows you to easily mock your fetch calls and return the response you need to fake the HTTP requests. It's easy to setup and you don't need a library like nock to get going and it uses Jest's built-in support for mocking under the surface. This means that any of the jest.fn() methods are also available. For more information on the jest mock API, check their docs here
It currently supports the mocking with the cross-fetch polyfill, so it supports Node.js and any browser-like runtime.
To setup your fetch mock you need to do the following things:
$ npm install --save-dev jest-fetch-mock
Create a setupJest file to setup the mock or add this to an existing setupFile. :
To setup for all tests
//setupJest.js or similar file
require('jest-fetch-mock').enableMocks()
Add the setupFile to your jest config in package.json:
"jest": {
"automock": false,
"setupFiles": [
"./setupJest.js"
]
}
With this done, you'll have fetch and fetchMock available on the global scope. Fetch will be used as usual by your code and you'll use fetchMock in your tests
Default not mocked
If you would like to have the 'fetchMock' available in all tests but not enabled then add fetchMock.dontMock() after the ...enableMocks() line in setupJest.js:
// adds the 'fetchMock' global variable and rewires 'fetch' global to call 'fetchMock' instead of the real implementation
require('jest-fetch-mock').enableMocks()
// changes default behavior of fetchMock to use the real 'fetch' implementation and not mock responses
fetchMock.dontMock()
If you want a single test file to return to the default behavior of mocking all responses, add the following to the
test file:
beforeEach(()=>{// if you have an existing `beforeEach` just add the following line to it
fetchMock.doMock()
})
To enable mocking for a specific URL only:
beforeEach(()=>{// if you have an existing `beforeEach` just add the following lines to it
If you have changed the default behavior to use the real implementation, you can guarantee the next call to fetch
will be mocked by using the mockOnce function:
fetchMock.mockOnce("the next call to fetch will always return this as the body")
This function behaves exactly like fetchMock.once but guarantees the next call to fetch will be mocked even if the
default behavior of fetchMock is to use the real implementation. You can safely convert all you fetchMock.once calls
to fetchMock.mockOnce without a risk of changing their behavior.
To setup for an individual test
For JavaScript add the following line to the start of your test case (before any other requires)
require('jest-fetch-mock').enableMocks()
For TypeScript/ES6 add the following lines to the start of your test case (before any other imports)
import{enableFetchMocks}from'jest-fetch-mock'
enableFetchMocks()
TypeScript importing
If you are using TypeScript and receive errors about the fetchMock global not existing,
add a global.d.ts file to the root of your project (or add the following line to an existing global file):
import'jest-fetch-mock'
If you prefer you can also just import the fetchMock in a test case.
importfetchMockfrom"jest-fetch-mock"
You may also need to edit your tsconfig.json and add "dom" and/or "es2015" and/or "esnext" to the 'compilerConfig.lib' property
Using with Create-React-App
If you are using Create-React-App (CRA), the code for setupTest.js above should be placed into src/setupTests.js in the root of your project. CRA automatically uses this filename by convention in the Jest configuration it generates. Similarly, changing to your package.json is not required as CRA handles this when generating your Jest configuration.
For Ejected Create React Apps ONLY:
Note: Keep in mind that if you decide to "eject" before creating src/setupTests.js, the resulting package.json file won't contain any reference to it, so you should manually create the property setupTestFrameworkScriptFile in the configuration for Jest, something like the following:
Each argument is an array taking [bodyOrFunction, init]
fetch.mockReject(errorOrFunction): fetch - Mock all fetch calls, letting them fail directly
fetch.mockRejectOnce(errorOrFunction): fetch - Let the next fetch call fail directly
fetch.mockAbort(): fetch - Causes all fetch calls to reject with an "Aborted!" error
fetch.mockAbortOnce(): fetch - Causes the next fetch call to reject with an "Aborted!" error
Functions
Instead of passing body, it is also possible to pass a function that returns a promise.
The promise should resolve with a string or an object containing body and init props
The function may take an optional "request" parameter of type http.Request:
fetch.mockResponse(req=>
req.url==='http://myapi/'
?callMyApi().then(res=>'ok')
:Promise.reject(newError('bad url'))
)
Note: the request "url" is parsed and then printed using the equivalent of new URL(input).href so it may not match exactly with the URL's passed to fetch if they are not fully qualified.
For example, passing "http://foo.com" to fetch will result in the request URL being "http://foo.com/" (note the trailing slash).
fetch.resetMocks() - Clear previously set mocks so they do not bleed into other mocks
fetch.enableMocks() - Enable fetch mocking by overriding global.fetch and mocking node-fetch
fetch.disableMocks() - Disable fetch mocking and restore default implementation of fetch and/or node-fetch
fetch.mock - The mock state for your fetch calls. Make assertions on the arguments given to fetch when called by the functions you are testing. For more information check the Jest docs
For information on the arguments body and init can take, you can look at the MDN docs on the Response Constructor function, which jest-fetch-mock uses under the surface.
Each mocked response or err
or will return a Mock Function. You can use methods like .toHaveBeenCalledWith to ensure that the mock function was called with specific arguments. For more methods detail, take a look at this.
Examples
In most of the complicated examples below, I am testing my action creators in Redux, but it doesn't have to be used with Redux.
Simple mock and assert
In this simple example I won't be using any libraries. It is a simple fetch request, in this case to google.com. First we setup the beforeEach callback to reset our mocks. This isn't strictly necessary in this example, but since we will probably be mocking fetch more than once, we need to reset it across our tests to assert on the arguments given to fetch.
Once we've done that we can start to mock our response. We want to give it an objectwith a data property and a string value of 12345 and wrap it in JSON.stringify to JSONify it. Here we use mockResponseOnce, but we could also use once, which is an alias for a call to mockResponseOnce
We then call the function that we want to test with the arguments we want to test with. In the then callback we assert we have got the correct data back.
Finally we can assert on the .mock state that Jest provides for us to test what arguments were given to fetch and how many times it was called
In this example I am mocking just one fetch call. Any additional fetch calls in the same function will also have the same mock response. For more complicated functions with multiple fetch calls, you can check out example 3.
importconfigureMockStorefrom'redux-mock-store'// mock store
importthunkfrom'redux-thunk'
constmiddlewares=[thunk]
constmockStore=configureMockStore(middlewares)
import{getAccessToken}from'./accessToken'
describe('Access token action creators',()=>{
it('dispatches the correct actions on successful fetch request',()=>{
In this example I am mocking just one fetch call but this time using the mockReject function to simulate a failed request. Any additional fetch calls in the same function will also have the same mock response. For more complicated functions with multiple fetch calls, you can check out example 3.
importconfigureMockStorefrom'redux-mock-store'// mock store
importthunkfrom'redux-thunk'
constmiddlewares=[thunk]
constmockStore=configureMockStore(middlewares)
import{getAccessToken}from'./accessToken'
describe('Access token action creators',()=>{
it('dispatches the correct actions on a failed fetch request',()=>{
Fetches can be mocked to act as if they were aborted during the request. This can be done in 4 ways:
Using `fetch.mockAborted()`
Using `fetch.mockAbortedOnce()`
Passing a request (or request init) with a 'signal' to fetch that has been aborted
Passing a request (or request init) with a 'signal' to fetch and a async function to `fetch.mockResponse` or `fetch.mockResponseOnce` that causes the signal to abort before returning the response
describe('Mocking aborts',()=>{
beforeEach(()=>{
fetch.resetMocks()
fetch.doMock()
jest.useFakeTimers()
})
afterEach(()=>{
jest.useRealTimers()
})
it('rejects with an Aborted! Error',()=>{
fetch.mockAbort()
expect(fetch('/')).rejects.toThrow('Aborted!')
})
it('rejects with an Aborted! Error once then mocks with empty response',async()=>{
In this next example, the store does not yet have a token, so we make a request to get an access token first. This means that we need to mock two different responses, one for each of the fetches. Here we can use fetch.mockResponseOnce or fetch.once to mock the response only once and call it twice. Because we return the mocked function, we can chain this jQuery style. It internally uses Jest's mockImplementationOnce. You can read more about it on the Jest documentation
importconfigureMockStorefrom'redux-mock-store'
importthunkfrom'redux-thunk'
constmiddlewares=[thunk]
constmockStore=configureMockStore(middlewares)
import{getAnimeDetails}from'./animeDetails'
describe('Anime details action creators',()=>{
it('dispatches requests for an access token before requesting for animeDetails',()=>{
fetch.mockResponses takes as many arguments as you give it, all of which are arrays representing each Response Object. It will then call the mockImplementationOnce for each response object you give it. This reduces the amount of boilerplate code you need to write. An alternative is to use .once and chain it multiple times if you don't like wrapping each response arguments in a tuple/array.
In this example our actionCreator calls fetch 4 times, once for each season of the year and then concatenates the results into one final array. You'd have to write fetch.mockResponseOnce 4 times to achieve the same thing:
describe('getYear action creator',()=>{
it('dispatches the correct actions on successful getSeason fetch request',()=>{
fetch.resetMocks resets the fetch mock to give fresh mock data in between tests. It only resets the fetch calls as to not disturb any other mocked functionality.
describe('getYear action creator',()=>{
beforeEach(()=>{
fetch.resetMocks();
});
it('dispatches the correct actions on successful getSeason fetch request',()=>{
Using fetch.mock to inspect the mock state of each fetch call
fetch.mock by default uses Jest's mocking functions. Therefore you can make assertions on the mock state. In this example we have an arbitrary function that makes a different fetch request based on the argument you pass to it. In our test, we run Jest's beforeEach() and make sure to reset our mock before each it() block as we will make assertions on the arguments we are passing to fetch(). The most uses property is the fetch.mock.calls array. It can give you information on each call, and their arguments which you can use for your expect() calls. Jest also comes with some nice aliases for the most used ones.
expect(fetch).toBeCalled()// alias for expect(fetch.mock.calls.length).toEqual(1);
expect(fetch).toBeCalledWith('https://twitter.com')// alias for expect(fetch.mock.calls[0][0]).toEqual();
})
})
Using functions to mock slow servers
By default you will want to have your fetch mock return immediately. However if you have some custom logic that needs to tests for slower servers, you can do this by passing it a function and returning a promise when your function resolves
// api.test.js
import{request}from'./api'
describe('testing timeouts',()=>{
it('resolves with function and timeout',async()=>{
In some test scenarios, you may want to temporarily disable (or enable) mocking for all requests or the next (or a certain number of) request(s).
You may want to only mock fetch requests to some URLs that match a given request path while in others you may want to mock
all requests except those matching a given request path. You may even want to conditionally mock based on request headers.
The conditional mock functions cause jest-fetch-mock to pass fetches through to the concrete fetch implementation conditionally.
Calling fetch.dontMock, fetch.doMock, fetch.doMockIf or fetch.dontMockIf overrides the default behavior
of mocking/not mocking all requests. fetch.dontMockOnce, fetch.doMockOnce, fetch.doMockOnceIf and fetch.dontMockOnceIf only overrides the behavior
for the next call to fetch, then returns to the default behavior (either mocking all requests or mocking the requests based on the last call to
fetch.dontMock, fetch.doMock, fetch.doMockIf and fetch.dontMockIf).
Calling fetch.resetMocks() will return to the default behavior of mocking all fetches with a text response of empty string.
fetch.dontMock() - Change the default behavior to not mock any fetches until fetch.resetMocks() or fetch.doMock() is called
fetch.doMock(bodyOrFunction?, responseInit?) - Reverses fetch.dontMock(). This is the default state after fetch.resetMocks()
fetch.dontMockOnce() - For the next fetch, do not mock then return to the default behavior for subsequent fetches. Can be chained.
fetch.doMockOnce(bodyOrFunction?, responseInit?) or fetch.mockOnce - For the next fetch, mock the response then return to the default behavior for subsequent fetches. Can be chained.
fetch.doMockIf(urlOrPredicate, bodyOrFunction?, responseInit?):fetch or fetch.mockIf - causes all fetches to be not be mocked unless they match the given string/RegExp/predicate
(i.e. "only mock 'fetch' if the request is for the given URL otherwise, use the real fetch implementation")
fetch.dontMockIf(urlOrPredicate, bodyOrFunction?, responseInit?):fetch - causes all fetches to be mocked unless they match the given string/RegExp/predicate
(i.e. "don't mock 'fetch' if the request is for the given URL, otherwise mock the request")
fetch.doMockOnceIf(urlOrPredicate, bodyOrFunction?, responseInit?):fetch or fetch.mockOnceIf - causes the next fetch to be mocked if it matches the given string/RegExp/predicate. Can be chained.
(i.e. "only mock 'fetch' if the next request is for the given URL otherwise, use the default behavior")
fetch.dontMockOnceIf(urlOrPredicate):fetch - causes the next fetch to be not be mocked if it matches the given string/RegExp/predicate. Can be chained.
(i.e. "don't mock 'fetch' if the next request is for the given URL, otherwise use the default behavior")
fetch.isMocking(input, init):boolean - test utility function to see if the given url/request would be mocked.
This is not a read only operation and any "MockOnce" will evaluate (and return to the default behavior)
For convenience, all the conditional mocking functions also accept optional parameters after the 1st parameter that call
mockResponse or mockResponseOnce respectively. This allows you to conditionally mock a response in a single call.