Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@knee-cola knee-cola commented Nov 21, 2017

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
You can’t perform that action at this time.