Skip to content

Instantly share code, notes, and snippets.

@markuso
Forked from pherris/superagent.js
Last active March 22, 2017 18:04
Show Gist options
  • Select an option

  • Save markuso/f7c59cf152f52c7a50eae5e3e6a56bb4 to your computer and use it in GitHub Desktop.

Select an option

Save markuso/f7c59cf152f52c7a50eae5e3e6a56bb4 to your computer and use it in GitHub Desktop.
Jest superagent mock
'use strict';
// Place this in the src root /__mocks__/superagent.js
let mockPayload;
let mockDelay;
let mockError;
let mockResponse = {
status: jest.fn().mockReturnValue(200),
ok: jest.fn().mockReturnValue(true),
body: {
walla: true
},
get: jest.fn(),
toError: jest.fn(),
};
const Request = jest.fn(() => ({
post: jest.fn().mockReturnThis(),
get: jest.fn().mockReturnThis(),
send: jest.fn(payload => {
mockPayload = payload;
return this;
}),
query: jest.fn().mockReturnThis(),
field: jest.fn().mockReturnThis(),
set: jest.fn().mockReturnThis(),
accept: jest.fn().mockReturnThis(),
timeout: jest.fn().mockReturnThis(),
end: jest.fn(callback => {
if (mockDelay) {
this.delayTimer = setTimeout(callback, 0, mockError, mockResponse);
return;
}
callback(mockError, mockResponse);
}),
}));
// Expose helper methods for tests to set
Request.__getMockPayload = () => {
return mockPayload;
};
Request.__getMockResponse = () => {
return mockResponse;
};
Request.__getMockError = () => {
return mockError;
};
Request.__setMockDelay = (boolValue) => {
mockDelay = boolValue;
};
Request.__setMockResponse = (res) => {
mockResponse = res;
};
Request.__setMockError = (err) => {
mockError = err;
};
module.exports = Request;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment