Gathering detailed insights and metrics for jest-fetch-mock
Gathering detailed insights and metrics for jest-fetch-mock
Gathering detailed insights and metrics for jest-fetch-mock
Gathering detailed insights and metrics for jest-fetch-mock
jest-fetch-mock-cache
caching mock implementation for jest-fetch-mock
vitest-fetch-mock
fetch mock for vitest
jest-mock
**Note:** More details on user side API can be found in [Jest documentation](https://jestjs.io/docs/mock-function-api).
jest-canvas-mock
Mock a canvas in your jest tests.
npm install jest-fetch-mock
55.7
Supply Chain
98.9
Quality
76.2
Maintenance
100
Vulnerability
100
License
Conditional Mocking, Request Based Responses, Enable/Disable Facade, and Abort Mocking
Published on 18 Dec 2019
Async version
Published on 26 Nov 2018
Switched from isomorphic-fetch to cross-fetch and added tests
Published on 10 Nov 2018
Promise.finally polyfill added and new .ts types
Published on 16 May 2018
Cleaned up docs and added `once` alias
Published on 21 Mar 2018
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
887 Stars
234 Commits
119 Forks
5 Watching
21 Branches
36 Contributors
Updated on 07 Nov 2024
JavaScript (90.48%)
TypeScript (9.52%)
Cumulative downloads
Total Downloads
Last day
-2.7%
278,076
Compared to previous day
Last week
4.1%
1,429,330
Compared to previous week
Last month
13.2%
5,830,876
Compared to previous month
Last year
30.9%
60,504,935
Compared to previous year
2
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.
fetch.mockResponses
fetch.resetMocks
fetch.mock
to inspect the mock state of each fetch callTo 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
. :
1//setupJest.js or similar file 2require('jest-fetch-mock').enableMocks()
Add the setupFile to your jest config in package.json
:
1"jest": { 2 "automock": false, 3 "resetMocks": false, 4 "setupFiles": [ 5 "./setupJest.js" 6 ] 7}
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
Note: the resetMocks
Jest configuration default was changed from false
to true
in Jest 4.0.1. Therefore the Jest configuration of setting it to false
is required if the setupJest.js
is what calls "enableMocks()" (i.e. in the above suggested setup) otherwise you will need to call "enableMocks()" in a "beforeEach" block.
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
:
1// adds the 'fetchMock' global variable and rewires 'fetch' global to call 'fetchMock' instead of the real implementation 2require('jest-fetch-mock').enableMocks() 3// changes default behavior of fetchMock to use the real 'fetch' implementation and not mock responses 4fetchMock.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:
1beforeEach(() => { 2 // if you have an existing `beforeEach` just add the following line to it 3 fetchMock.doMock() 4})
To enable mocking for a specific URL only:
1beforeEach(() => { 2 // if you have an existing `beforeEach` just add the following lines to it 3 fetchMock.mockIf(/^https?:\/\/example.com.*$/, async (req) => { 4 if (req.url.endsWith('/path1')) { 5 return 'some response body' 6 } else if (req.url.endsWith('/path2')) { 7 return { 8 body: 'another response body', 9 headers: { 10 'X-Some-Response-Header': 'Some header value' 11 } 12 } 13 } else { 14 return { 15 status: 404, 16 body: 'Not Found' 17 } 18 } 19 }) 20})
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:
1fetchMock.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.
For JavaScript add the following line to the start of your test case (before any other requires)
1require('jest-fetch-mock').enableMocks()
For TypeScript/ES6 add the following lines to the start of your test case (before any other imports)
1import { enableFetchMocks } from 'jest-fetch-mock' 2enableFetchMocks()
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):
1import 'jest-fetch-mock'
If you prefer you can also just import the fetchMock in a test case.
1import fetchMock from '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
If you are using Create-React-App (CRA), the code for setupJest.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.
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:
1"jest": { 2 "setupTestFrameworkScriptFile": "<rootDir>/src/setupTests.js" 3 }
fetch.mockResponse(bodyOrFunction, init): fetch
- Mock all fetch callsfetch.mockResponseOnce(bodyOrFunction, init): fetch
- Mock each fetch call independentlyfetch.once(bodyOrFunction, init): fetch
- Alias for mockResponseOnce(bodyOrFunction, init)
fetch.mockResponses(...responses): fetch
- Mock multiple fetch calls independently
[bodyOrFunction, init]
fetch.mockReject(errorOrFunction): fetch
- Mock all fetch calls, letting them fail directlyfetch.mockRejectOnce(errorOrFunction): fetch
- Let the next fetch call fail directlyfetch.mockAbort(): fetch
- Causes all fetch calls to reject with an "Aborted!" errorfetch.mockAbortOnce(): fetch
- Causes the next fetch call to reject with an "Aborted!" errorInstead 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
i.e:
1fetch.mockResponse(() => callMyApi().then(res => ({ body: 'ok' }))) 2// OR 3fetch.mockResponse(() => callMyApi().then(res => 'ok'))
The function may take an optional "request" parameter of type http.Request
:
1fetch.mockResponse(req =>
2 req.url === 'http://myapi/'
3 ? callMyApi().then(res => 'ok')
4 : Promise.reject(new Error('bad url'))
5)
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).
The same goes for rejects:
1fetch.mockReject(() =>
2 doMyAsyncJob().then(res => Promise.reject(res.errorToRaise))
3)
4// OR
5fetch.mockReject(req =>
6 req.headers.get('content-type') === 'text/plain'
7 ? Promise.reject('invalid content type')
8 : doMyAsyncJob().then(res => Promise.reject(res.errorToRaise))
9)
fetch.resetMocks()
- Clear previously set mocks so they do not bleed into other mocksfetch.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 docsFor 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.
https://developer.mozilla.org/en-US/docs/Web/API/Response/Response
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.
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.
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. Make sure the function wrapping your test is marked as async.
Once we've done that we can start to mock our response. We want to give it an object with 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. We use await
to wait until the response resolves, and then 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
1//api.js 2export function APIRequest(who) { 3 if (who === 'google') { 4 return fetch('https://google.com').then(res => res.json()) 5 } else { 6 return 'no argument provided' 7 } 8}
1//api.test.js 2import { APIRequest } from './api' 3 4describe('testing api', () => { 5 beforeEach(() => { 6 fetch.resetMocks() 7 }) 8 9 it('calls google and returns data to me', async () => { 10 fetch.mockResponseOnce(JSON.stringify({ data: '12345' })) 11 12 //assert on the response 13 const res = await APIRequest('google') 14 expect(res.data).toEqual('12345') 15 16 //assert on the times called and arguments given to fetch 17 expect(fetch.mock.calls.length).toEqual(1) 18 expect(fetch.mock.calls[0][0]).toEqual('https://google.com') 19 }) 20})
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.
1import configureMockStore from 'redux-mock-store' // mock store 2import thunk from 'redux-thunk' 3 4const middlewares = [thunk] 5const mockStore = configureMockStore(middlewares) 6 7import { getAccessToken } from './accessToken' 8 9describe('Access token action creators', () => { 10 it('dispatches the correct actions on successful fetch request', () => { 11 fetch.mockResponse(JSON.stringify({ access_token: '12345' })) 12 13 const expectedActions = [ 14 { type: 'SET_ACCESS_TOKEN', token: { access_token: '12345' } } 15 ] 16 const store = mockStore({ config: { token: '' } }) 17 18 return ( 19 store 20 .dispatch(getAccessToken()) 21 //getAccessToken contains the fetch call 22 .then(() => { 23 // return of async actions 24 expect(store.getActions()).toEqual(expectedActions) 25 }) 26 ) 27 }) 28})
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.
1import configureMockStore from 'redux-mock-store' // mock store 2import thunk from 'redux-thunk' 3 4const middlewares = [thunk] 5const mockStore = configureMockStore(middlewares) 6 7import { getAccessToken } from './accessToken' 8 9describe('Access token action creators', () => { 10 it('dispatches the correct actions on a failed fetch request', () => { 11 fetch.mockReject(new Error('fake error message')) 12 13 const expectedActions = [ 14 { type: 'SET_ACCESS_TOKEN_FAILED', error: { status: 503 } } 15 ] 16 const store = mockStore({ config: { token: '' } }) 17 18 return ( 19 store 20 .dispatch(getAccessToken()) 21 //getAccessToken contains the fetch call 22 .then(() => { 23 // return of async actions 24 expect(store.getActions()).toEqual(expectedActions) 25 }) 26 ) 27 }) 28})
Fetches can be mocked to act as if they were aborted during the request. This can be done in 4 ways:
1describe('Mocking aborts', () => { 2 beforeEach(() => { 3 fetch.resetMocks() 4 fetch.doMock() 5 jest.useFakeTimers() 6 }) 7 afterEach(() => { 8 jest.useRealTimers() 9 }) 10 11 it('rejects with an Aborted! Error', () => { 12 fetch.mockAbort() 13 expect(fetch('/')).rejects.toThrow('Aborted!') 14 }) 15 it('rejects with an Aborted! Error once then mocks with empty response', async () => { 16 fetch.mockAbortOnce() 17 await expect(fetch('/')).rejects.toThrow('Aborted!') 18 await expect(request()).resolves.toEqual('') 19 }) 20 21 it('throws when passed an already aborted abort signal', () => { 22 const c = new AbortController() 23 c.abort() 24 expect(() => fetch('/', { signal: c.signal })).toThrow('Aborted!') 25 }) 26 27 it('rejects when aborted before resolved', async () => { 28 const c = new AbortController() 29 fetch.mockResponse(async () => { 30 jest.advanceTimersByTime(60) 31 return '' 32 }) 33 setTimeout(() => c.abort(), 50) 34 await expect(fetch('/', { signal: c.signal })).rejects.toThrow('Aborted!') 35 }) 36})
Set the counter option >= 1 in the response init object to mock a redirected response https://developer.mozilla.org/en-US/docs/Web/API/Response/redirected. Note, this will only work in Node.js as it's a feature of node fetch's response class https://github.com/node-fetch/node-fetch/blob/master/src/response.js#L39.
1fetchMock.mockResponse("<main></main>", { 2 counter: 1, 3 status: 200, 4 statusText: "ok", 5});
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
1import configureMockStore from 'redux-mock-store' 2import thunk from 'redux-thunk' 3 4const middlewares = [thunk] 5const mockStore = configureMockStore(middlewares) 6 7import { getAnimeDetails } from './animeDetails' 8 9describe('Anime details action creators', () => { 10 it('dispatches requests for an access token before requesting for animeDetails', () => { 11 fetch 12 .once(JSON.stringify({ access_token: '12345' })) 13 .once(JSON.stringify({ name: 'naruto' })) 14 15 const expectedActions = [ 16 { type: 'SET_ACCESS_TOKEN', token: { access_token: '12345' } }, 17 { type: 'SET_ANIME_DETAILS', animeDetails: { name: 'naruto' } } 18 ] 19 const store = mockStore({ config: { token: null } }) 20 21 return ( 22 store 23 .dispatch(getAnimeDetails('21049')) 24 //getAnimeDetails contains the 2 fetch calls 25 .then(() => { 26 // return of async actions 27 expect(store.getActions()).toEqual(expectedActions) 28 }) 29 ) 30 }) 31})
fetch.mockResponses
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:
1describe('getYear action creator', () => { 2 it('dispatches the correct actions on successful getSeason fetch request', () => { 3 fetch.mockResponses( 4 [ 5 JSON.stringify([{ name: 'naruto', average_score: 79 }]), 6 { status: 200 } 7 ], 8 [ 9 JSON.stringify([{ name: 'bleach', average_score: 68 }]), 10 { status: 200 } 11 ], 12 [ 13 JSON.stringify([{ name: 'one piece', average_score: 80 }]), 14 { status: 200 } 15 ], 16 [ 17 JSON.stringify([{ name: 'shingeki', average_score: 91 }]), 18 { status: 200 } 19 ] 20 ) 21 22 const expectedActions = [ 23 { 24 type: 'FETCH_ANIMELIST_REQUEST' 25 }, 26 { 27 type: 'SET_YEAR', 28 payload: { 29 animes: [ 30 { name: 'naruto', average_score: 7.9 }, 31 { name: 'bleach', average_score: 6.8 }, 32 { name: 'one piece', average_score: 8 }, 33 { name: 'shingeki', average_score: 9.1 } 34 ], 35 year: 2016 36 } 37 }, 38 { 39 type: 'FETCH_ANIMELIST_COMPLETE' 40 } 41 ] 42 const store = mockStore({ 43 config: { 44 token: { access_token: 'wtw45CmyEuh4P621IDVxWkgVr5QwTg3wXEc4Z7Cv' } 45 }, 46 years: [] 47 }) 48 49 return ( 50 store 51 .dispatch(getYear(2016)) 52 //This calls fetch 4 times, once for each season 53 .then(() => { 54 // return of async actions 55 expect(store.getActions()).toEqual(expectedActions) 56 }) 57 ) 58 }) 59})
fetch.resetMocks
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.
1describe('getYear action creator', () => { 2 beforeEach(() => { 3 fetch.resetMocks(); 4 }); 5 it('dispatches the correct actions on successful getSeason fetch request', () => { 6 7 fetch.mockResponses( 8 [ 9 JSON.stringify([ {name: 'naruto', average_score: 79} ]), { status: 200} 10 ], 11 [ 12 JSON.stringify([ {name: 'bleach', average_score: 68} ]), { status: 200} 13 ] 14 ) 15 16 const expectedActions = [ 17 { 18 type: 'FETCH_ANIMELIST_REQUEST' 19 }, 20 { 21 type: 'SET_YEAR', 22 payload: { 23 animes: [ 24 {name: 'naruto', average_score: 7.9}, 25 {name: 'bleach', average_score: 6.8} 26 ], 27 year: 2016, 28 } 29 }, 30 { 31 type: 'FETCH_ANIMELIST_COMPLETE' 32 } 33 ] 34 const store = mockStore({ 35 config: { token: { access_token: 'wtw45CmyEuh4P621IDVxWkgVr5QwTg3wXEc4Z7Cv' }}, 36 years: [] 37 }) 38 39 return store.dispatch(getYear(2016)) 40 //This calls fetch 2 times, once for each season 41 .then(() => { // return of async actions 42 expect(store.getActions()).toEqual(expectedActions) 43 }) 44 }); 45 it('dispatches the correct actions on successful getSeason fetch request', () => { 46 47 fetch.mockResponses( 48 [ 49 JSON.stringify([ {name: 'bleach', average_score: 68} ]), { status: 200} 50 ], 51 [ 52 JSON.stringify([ {name: 'one piece', average_score: 80} ]), { status: 200} 53 ], 54 [ 55 JSON.stringify([ {name: 'shingeki', average_score: 91} ]), { status: 200} 56 ] 57 ) 58 59 const expectedActions = [ 60 { 61 type: 'FETCH_ANIMELIST_REQUEST' 62 }, 63 { 64 type: 'SET_YEAR', 65 payload: { 66 animes: [ 67 {name: 'bleach', average_score: 6.8}, 68 {name: 'one piece', average_score: 8}, 69 {name: 'shingeki', average_score: 9.1} 70 ], 71 year: 2016, 72 } 73 }, 74 { 75 type: 'FETCH_ANIMELIST_COMPLETE' 76 } 77 ] 78 const store = mockStore({ 79 config: { token: { access_token: 'wtw45CmyEuh4P621IDVxWkgVr5QwTg3wXEc4Z7Cv' }}, 80 years: [] 81 }) 82 83 return store.dispatch(getYear(2016)) 84 //This calls fetch 3 times, once for each season 85 .then(() => { // return of async actions 86 expect(store.getActions()).toEqual(expectedActions) 87 }) 88 , 89 90 }) 91})
fetch.mock
to inspect the mock state of each fetch callfetch.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.
1// api.js 2 3import 'cross-fetch' 4 5export function APIRequest(who) { 6 if (who === 'facebook') { 7 return fetch('https://facebook.com') 8 } else if (who === 'twitter') { 9 return fetch('https://twitter.com') 10 } else { 11 return fetch('https://google.com') 12 } 13}
1// api.test.js 2import { APIRequest } from './api' 3 4describe('testing api', () => { 5 beforeEach(() => { 6 fetch.resetMocks() 7 }) 8 9 it('calls google by default', () => { 10 fetch.mockResponse(JSON.stringify({ secret_data: '12345' })) 11 APIRequest() 12 13 expect(fetch.mock.calls.length).toEqual(1) 14 expect(fetch.mock.calls[0][0]).toEqual('https://google.com') 15 }) 16 17 it('calls facebook', () => { 18 fetch.mockResponse(JSON.stringify({ secret_data: '12345' })) 19 APIRequest('facebook') 20 21 expect(fetch.mock.calls.length).toEqual(2) 22 expect(fetch.mock.calls[0][0]).toEqual( 23 'https://facebook.com/someOtherResource' 24 ) 25 expect(fetch.mock.calls[1][0]).toEqual('https://facebook.com') 26 }) 27 28 it('calls twitter', () => { 29 fetch.mockResponse(JSON.stringify({ secret_data: '12345' })) 30 APIRequest('twitter') 31 32 expect(fetch).toBeCalled() // alias for expect(fetch.mock.calls.length).toEqual(1); 33 expect(fetch).toBeCalledWith('https://twitter.com') // alias for expect(fetch.mock.calls[0][0]).toEqual(); 34 }) 35})
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
1// api.test.js 2import { request } from './api' 3 4describe('testing timeouts', () => { 5 it('resolves with function and timeout', async () => { 6 fetch.mockResponseOnce( 7 () => 8 new Promise(resolve => setTimeout(() => resolve({ body: 'ok' }), 100)) 9 ) 10 try { 11 const response = await request() 12 expect(response).toEqual('ok') 13 } catch (e) { 14 throw e 15 } 16 }) 17})
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 calledfetch.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.
1 2describe('conditional mocking', () => { 3 const realResponse = 'REAL FETCH RESPONSE' 4 const mockedDefaultResponse = 'MOCKED DEFAULT RESPONSE' 5 const testUrl = defaultRequestUri 6 let crossFetchSpy 7 beforeEach(() => { 8 fetch.resetMocks() 9 fetch.mockResponse(mockedDefaultResponse) 10 crossFetchSpy = jest 11 .spyOn(require('cross-fetch'), 'fetch') 12 .mockImplementation(async () => 13 Promise.resolve(new Response(realResponse)) 14 ) 15 }) 16 17 afterEach(() => { 18 crossFetchSpy.mockRestore() 19 }) 20 21 const expectMocked = async (uri, response = mockedDefaultResponse) => { 22 return expect(request(uri)).resolves.toEqual(response) 23 } 24 const expectUnmocked = async uri => { 25 return expect(request(uri)).resolves.toEqual(realResponse) 26 } 27 28 describe('once', () => { 29 it('default', async () => { 30 const otherResponse = 'other response' 31 fetch.once(otherResponse) 32 await expectMocked(defaultRequestUri, otherResponse) 33 await expectMocked() 34 }) 35 it('dont mock once then mock twice', async () => { 36 const otherResponse = 'other response' 37 fetch 38 .dontMockOnce() 39 .once(otherResponse) 40 .once(otherResponse) 41 42 await expectUnmocked() 43 await expectMocked(defaultRequestUri, otherResponse) 44 await expectMocked() 45 }) 46 }) 47 48 describe('doMockIf', () => { 49 it("doesn't mock normally", async () => { 50 fetch.doMockIf('http://foo') 51 await expectUnmocked() 52 await expectUnmocked() 53 }) 54 it('mocks when matches string', async () => { 55 fetch.doMockIf(testUrl) 56 await expectMocked() 57 await expectMocked() 58 }) 59 it('mocks when matches regex', async () => { 60 fetch.doMockIf(new RegExp(testUrl)) 61 await expectMocked() 62 await expectMocked() 63 }) 64 it('mocks when matches predicate', async () => { 65 fetch.doMockIf(input => input.url === testUrl) 66 await expectMocked() 67 await expectMocked() 68 }) 69 }) 70 71 describe('dontMockIf', () => { 72 it('mocks normally', async () => { 73 fetch.dontMockIf('http://foo') 74 await expectMocked() 75 await expectMocked() 76 }) 77 it('doesnt mock when matches string', async () => { 78 fetch.dontMockIf(testUrl) 79 await expectUnmocked() 80 await expectUnmocked() 81 }) 82 it('doesnt mock when matches regex', async () => { 83 fetch.dontMockIf(new RegExp(testUrl)) 84 await expectUnmocked() 85 await expectUnmocked() 86 }) 87 it('doesnt mock when matches predicate', async () => { 88 fetch.dontMockIf(input => input.url === testUrl) 89 await expectUnmocked() 90 await expectUnmocked() 91 }) 92 }) 93 94 describe('doMockOnceIf (default mocked)', () => { 95 it("doesn't mock normally", async () => { 96 fetch.doMockOnceIf('http://foo') 97 await expectUnmocked() 98 await expectMocked() 99 }) 100 it('mocks when matches string', async () => { 101 fetch.doMockOnceIf(testUrl) 102 await expectMocked() 103 await expectMocked() 104 }) 105 it('mocks when matches regex', async () => { 106 fetch.doMockOnceIf(new RegExp(testUrl)) 107 await expectMocked() 108 await expectMocked() 109 }) 110 it('mocks when matches predicate', async () => { 111 fetch.doMockOnceIf(input => input.url === testUrl) 112 await expectMocked() 113 await expectMocked() 114 }) 115 }) 116 117 describe('dontMockOnceIf (default mocked)', () => { 118 it('mocks normally', async () => { 119 fetch.dontMockOnceIf('http://foo') 120 await expectMocked() 121 await expectMocked() 122 }) 123 it('doesnt mock when matches string', async () => { 124 fetch.dontMockOnceIf(testUrl) 125 await expectUnmocked() 126 await expectMocked() 127 }) 128 it('doesnt mock when matches regex', async () => { 129 fetch.dontMockOnceIf(new RegExp(testUrl)) 130 await expectUnmocked() 131 await expectMocked() 132 }) 133 it('doesnt mock when matches predicate', async () => { 134 fetch.dontMockOnceIf(input => input.url === testUrl) 135 await expectUnmocked() 136 await expectMocked() 137 }) 138 }) 139 140 describe('doMockOnceIf (default unmocked)', () => { 141 beforeEach(() => { 142 fetch.dontMock() 143 }) 144 it("doesn't mock normally", async () => { 145 fetch.doMockOnceIf('http://foo') 146 await expectUnmocked() 147 await expectUnmocked() 148 }) 149 it('mocks when matches string', async () => { 150 fetch.doMockOnceIf(testUrl) 151 await expectMocked() 152 await expectUnmocked() 153 }) 154 it('mocks when matches regex', async () => { 155 fetch.doMockOnceIf(new RegExp(testUrl)) 156 await expectMocked() 157 await expectUnmocked() 158 }) 159 it('mocks when matches predicate', async () => { 160 fetch.doMockOnceIf(input => input.url === testUrl) 161 await expectMocked() 162 await expectUnmocked() 163 }) 164 }) 165 166 describe('dontMockOnceIf (default unmocked)', () => { 167 beforeEach(() => { 168 fetch.dontMock() 169 }) 170 it('mocks normally', async () => { 171 fetch.dontMockOnceIf('http://foo') 172 await expectMocked() 173 await expectUnmocked() 174 }) 175 it('doesnt mock when matches string', async () => { 176 fetch.dontMockOnceIf(testUrl) 177 await expectUnmocked() 178 await expectUnmocked() 179 }) 180 it('doesnt mock when matches regex', async () => { 181 fetch.dontMockOnceIf(new RegExp(testUrl)) 182 await expectUnmocked() 183 await expectUnmocked() 184 }) 185 it('doesnt mock when matches predicate', async () => { 186 fetch.dontMockOnceIf(input => input.url === testUrl) 187 await expectUnmocked() 188 await expectUnmocked() 189 }) 190 }) 191 192 describe('dont/do mock', () => { 193 test('dontMock', async () => { 194 fetch.dontMock() 195 await expectUnmocked() 196 await expectUnmocked() 197 }) 198 test('dontMockOnce', async () => { 199 fetch.dontMockOnce() 200 await expectUnmocked() 201 await expectMocked() 202 }) 203 test('doMock', async () => { 204 fetch.dontMock() 205 fetch.doMock() 206 await expectMocked() 207 await expectMocked() 208 }) 209 test('doMockOnce', async () => { 210 fetch.dontMock() 211 fetch.doMockOnce() 212 await expectMocked() 213 await expectUnmocked() 214 }) 215 }) 216
1const expectMocked = async (uri, response = mockedDefaultResponse) => {
2 return expect(request(uri)).resolves.toEqual(response)
3}
4const expectUnmocked = async uri => {
5 return expect(request(uri)).resolves.toEqual(realResponse)
6}
7
8describe('conditional mocking complex', () => {
9 const realResponse = 'REAL FETCH RESPONSE'
10 const mockedDefaultResponse = 'MOCKED DEFAULT RESPONSE'
11 const testUrl = defaultRequestUri
12 let crossFetchSpy
13 beforeEach(() => {
14 fetch.resetMocks()
15 fetch.mockResponse(mockedDefaultResponse)
16 crossFetchSpy = jest
17 .spyOn(require('cross-fetch'), 'fetch')
18 .mockImplementation(async () =>
19 Promise.resolve(new Response(realResponse))
20 )
21 })
22
23 afterEach(() => {
24 crossFetchSpy.mockRestore()
25 })
26
27 describe('complex example', () => {
28 const alternativeUrl = 'http://bar'
29 const alternativeBody = 'ALTERNATIVE RESPONSE'
30 beforeEach(() => {
31 fetch
32 // .mockResponse(mockedDefaultResponse) // set above - here for clarity
33 .mockResponseOnce('1') // 1
34 .mockResponseOnce('2') // 2
35 .mockResponseOnce(async uri =>
36 uri === alternativeUrl ? alternativeBody : '3'
37 ) // 3
38 .mockResponseOnce('4') // 4
39 .mockResponseOnce('5') // 5
40 .mockResponseOnce(async uri =>
41 uri === alternativeUrl ? alternativeBody : mockedDefaultResponse
42 ) // 6
43 })
44
45 describe('default (`doMock`)', () => {
46 beforeEach(() => {
47 fetch
48 // .doMock() // the default - here for clarify
49 .dontMockOnceIf(alternativeUrl)
50 .doMockOnceIf(alternativeUrl)
51 .doMockOnce()
52 .dontMockOnce()
53 })
54
55 test('defaultRequestUri', async () => {
56 await expectMocked(defaultRequestUri, '1') // 1
57 await expectUnmocked(defaultRequestUri) // 2
58 await expectMocked(defaultRequestUri, '3') // 3
59 await expectUnmocked(defaultRequestUri) // 4
60 // after .once('..')
61 await expectMocked(defaultRequestUri, '5') // 5
62 await expectMocked(defaultRequestUri, mockedDefaultResponse) // 6
63 // default 'isMocked' (not 'Once')
64 await expectMocked(defaultRequestUri, mockedDefaultResponse) // 7
65 })
66
67 test('alternativeUrl', async () => {
68 await expectUnmocked(alternativeUrl) // 1
69 await expectMocked(alternativeUrl, '2') // 2
70 await expectMocked(alternativeUrl, alternativeBody) // 3
71 await expectUnmocked(alternativeUrl) // 4
72 // after .once('..')
73 await expectMocked(alternativeUrl, '5') // 5
74 await expectMocked(alternativeUrl, alternativeBody) // 6
75 // default 'isMocked' (not 'Once')
76 await expectMocked(alternativeUrl, mockedDefaultResponse) // 7
77 })
78 })
79
80 describe('dontMock', () => {
81 beforeEach(() => {
82 fetch
83 .dontMock()
84 .dontMockOnceIf(alternativeUrl)
85 .doMockOnceIf(alternativeUrl)
86 .doMockOnce()
87 .dontMockOnce()
88 })
89
90 test('defaultRequestUri', async () => {
91 await expectMocked(defaultRequestUri, '1') // 1
92 await expectUnmocked(defaultRequestUri) // 2
93 await expectMocked(defaultRequestUri, '3') // 3
94 await expectUnmocked(defaultRequestUri) // 4
95 // after .once('..')
96 await expectUnmocked(defaultRequestUri) // 5
97 await expectUnmocked(defaultRequestUri) // 6
98 // default 'isMocked' (not 'Once')
99 await expectUnmocked(defaultRequestUri) // 7
100 })
101
102 test('alternativeUrl', async () => {
103 await expectUnmocked(alternativeUrl) // 1
104 await expectMocked(alternativeUrl, '2') // 2
105 await expectMocked(alternativeUrl, alternativeBody) // 3
106 await expectUnmocked(alternativeUrl) // 4
107 // after .once('..')
108 await expectUnmocked(alternativeUrl) // 5
109 await expectUnmocked(alternativeUrl) // 6
110 // default 'isMocked' (not 'Once')
111 await expectUnmocked(alternativeUrl) // 7
112 })
113 })
114
115 describe('doMockIf(alternativeUrl)', () => {
116 beforeEach(() => {
117 fetch
118 .doMockIf(alternativeUrl)
119 .dontMockOnceIf(alternativeUrl)
120 .doMockOnceIf(alternativeUrl)
121 .doMockOnce()
122 .dontMockOnce()
123 })
124
125 test('defaultRequestUri', async () => {
126 await expectMocked(defaultRequestUri, '1') // 1
127 await expectUnmocked(defaultRequestUri) // 2
128 await expectMocked(defaultRequestUri, '3') // 3
129 await expectUnmocked(defaultRequestUri) // 4
130 // after .once('..')
131 await expectUnmocked(defaultRequestUri) // 5
132 await expectUnmocked(defaultRequestUri) // 6
133 // default 'isMocked' (not 'Once')
134 await expectUnmocked(defaultRequestUri) // 7
135 })
136
137 test('alternativeUrl', async () => {
138 await expectUnmocked(alternativeUrl) // 1
139 await expectMocked(alternativeUrl, '2') // 2
140 await expectMocked(alternativeUrl, alternativeBody) // 3
141 await expectUnmocked(alternativeUrl) // 4
142 // after .once('..')
143 await expectMocked(alternativeUrl, '5') // 5
144 await expectMocked(alternativeUrl, alternativeBody) // 6
145 // default 'isMocked' (not 'Once')
146 await expectMocked(alternativeUrl, mockedDefaultResponse) // 7
147 })
148 })
149
150 describe('dontMockIf(alternativeUrl)', () => {
151 beforeEach(() => {
152 fetch
153 .dontMockIf(alternativeUrl)
154 .dontMockOnceIf(alternativeUrl)
155 .doMockOnceIf(alternativeUrl)
156 .doMockOnce()
157 .dontMockOnce()
158 })
159
160 test('defaultRequestUri', async () => {
161 await expectMocked(defaultRequestUri, '1') // 1
162 await expectUnmocked(defaultRequestUri) // 2
163 await expectMocked(defaultRequestUri, '3') // 3
164 await expectUnmocked(defaultRequestUri) // 4
165 // after .once('..')
166 await expectMocked(defaultRequestUri, '5') // 5
167 await expectMocked(defaultRequestUri, mockedDefaultResponse) // 6
168 // default 'isMocked' (not 'Once')
169 await expectMocked(defaultRequestUri, mockedDefaultResponse) // 7
170 })
171
172 test('alternativeUrl', async () => {
173 await expectUnmocked(alternativeUrl) // 1
174 await expectMocked(alternativeUrl, '2') // 2
175 await expectMocked(alternativeUrl, alternativeBody) // 3
176 await expectUnmocked(alternativeUrl) // 4
177 // after .once('..')
178 await expectUnmocked(alternativeUrl) // 5
179 await expectUnmocked(alternativeUrl) // 6
180 // default 'isMocked' (not 'Once')
181 await expectUnmocked(alternativeUrl) // 7
182 })
183 })
184 })
185})
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 11/14 approved changesets -- score normalized to 7
Reason
3 existing vulnerabilities detected
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-18
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More