Skip to content

Instantly share code, notes, and snippets.

@tux4
Last active September 22, 2022 12:43
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tux4/36006a1859323f779ab0 to your computer and use it in GitHub Desktop.
Save tux4/36006a1859323f779ab0 to your computer and use it in GitHub Desktop.
Jest mock for axios.js
/* 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;
});
});
/* 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;
@knee-cola
Copy link

There's a bug in axios.js @ 34.

Instead mockReseponse it should say mockResponse.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment