Skip to content

Instantly share code, notes, and snippets.

@charleskorn
Forked from pherris/superagent.js
Last active September 6, 2021 06:40
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save charleskorn/1d8a3d728b32f1f75768 to your computer and use it in GitHub Desktop.
Save charleskorn/1d8a3d728b32f1f75768 to your computer and use it in GitHub Desktop.
A Jest mock for superagent. Place in your __mocks__ directory.
'use strict';
var mockDelay;
var mockError;
var mockResponse = {
status: function () {
return 200;
},
ok: true,
get: jest.genMockFunction(),
toError: jest.genMockFunction()
};
var Request = {
post: jest.genMockFunction().mockReturnThis(),
get: jest.genMockFunction().mockReturnThis(),
send: jest.genMockFunction().mockReturnThis(),
query: jest.genMockFunction().mockReturnThis(),
field: jest.genMockFunction().mockReturnThis(),
set: jest.genMockFunction().mockReturnThis(),
accept: jest.genMockFunction().mockReturnThis(),
timeout: jest.genMockFunction().mockReturnThis(),
end: jest.genMockFunction().mockImplementation(function (callback) {
if (mockDelay) {
this.delayTimer = setTimeout(callback, 0, mockError, mockResponse);
return;
}
callback(mockError, mockResponse);
}),
__setMockDelay: function (boolValue) {
mockDelay = boolValue;
},
__setMockResponse: function (mockRes) {
mockResponse = mockRes;
},
__setMockError: function (mockErr) {
mockError = mockErr;
},
__setMockResponseBody: function (body) {
mockResponse.body = body;
}
};
module.exports = Request;
@gbalbuena
Copy link

Did an update to support es6 and the last version of jest

You can find it here: https://gist.github.com/gbalbuena/3ec499535d435712ce16c1eced9f5502

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