Last active
September 22, 2022 12:43
-
-
Save tux4/36006a1859323f779ab0 to your computer and use it in GitHub Desktop.
Jest mock for axios.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Jest test of axios XHR calls */ | |
describe('axios', function() { | |
var axios; | |
beforeEach(function() { | |
axios = require('axios'); | |
}); | |
pit('successful mock HTTP request', function() { | |
var reqP = axios | |
.get('http://someurl') | |
.then(function(res){ | |
expect(res.status).toBe(200); | |
}); | |
axios.finishRequest(); | |
return reqP; | |
}); | |
pit('failed mock HTTP request', function() { | |
axios._setMockError({status: 404}); | |
var reqP = axios | |
.get('http://someurl') | |
.catch(function(err){ | |
expect(err.status).toBe(404); | |
}); | |
axios.finishRequest(); | |
return reqP; | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Axios mock to be placed in __mocks__ */ | |
'use strict'; | |
var Promise = require.requireActual('bluebird'); | |
var mockDelay = 1; | |
var mockError; | |
var mockResponse = { | |
data: {}, | |
status: 200, | |
statusText: 'OK', | |
headers: {}, | |
config: {}, | |
}; | |
var axiosMock = jest.genMockFromModule('axios'); | |
function req() { | |
return new Promise(function(resolve, reject) { | |
axiosMock.delayTimer = setTimeout(function() { | |
if (mockError) { | |
reject(mockError); | |
} else { | |
resolve(mockResponse); | |
} | |
}, mockDelay); | |
}); | |
}; | |
axiosMock.get.mockImplementation(req); | |
axiosMock.post.mockImplementation(req); | |
axiosMock.put.mockImplementation(req); | |
axiosMock.delete.mockImplementation(req); | |
axiosMock._setMockError = (mE) => { mockError = mE }; | |
axiosMock._setMockResponse = (mR) => { mockReseponse = mR }; | |
axiosMock._setDelay = (mD) => { mockDelay = mD }; | |
axiosMock.finishRequest = () => { jest.runOnlyPendingTimers() }; | |
module.exports = axiosMock; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There's a bug in
axios.js
@ 34.Instead
mockReseponse
it should saymockResponse
.