-
-
Save gbalbuena/3ec499535d435712ce16c1eced9f5502 to your computer and use it in GitHub Desktop.
A Jest mock for superagent. Place in your __mocks__ directory.
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
llet mockDelay; | |
let mockError; | |
let mockResponse = { | |
get: jest.fn(), | |
ok: true, | |
status: 200, | |
toError: jest.fn(), | |
}; | |
let mockResponseBodies; | |
let responseBodiesIndex; | |
const Request = { | |
__setMockDelay(boolValue) { | |
mockDelay = boolValue; | |
}, | |
__setMockError(mockErr) { | |
mockError = mockErr; | |
}, | |
__setMockResponse(mockRes) { | |
mockResponse = mockRes; | |
}, | |
__setMockResponseBodies(bodies) { | |
mockResponseBodies = bodies; | |
responseBodiesIndex = -1; | |
}, | |
__setMockResponseBody(body) { | |
mockResponse.body = body; | |
responseBodiesIndex = undefined; | |
}, | |
accept: jest.fn().mockReturnThis(), | |
catch: jest.fn().mockReturnThis(), | |
delete: jest.fn().mockReturnThis(), | |
end: jest.fn().mockImplementation(callback => { | |
if (mockDelay) { | |
this.delayTimer = setTimeout(callback, 0, mockError, mockResponse); | |
return; | |
} | |
callback(mockError, mockResponse); | |
}), | |
field: jest.fn().mockReturnThis(), | |
get: jest.fn().mockReturnThis(), | |
head: jest.fn().mockReturnThis(), | |
patch: jest.fn().mockReturnThis(), | |
post: jest.fn().mockReturnThis(), | |
put: jest.fn().mockReturnThis(), | |
query: jest.fn().mockReturnThis(), | |
redirects: jest.fn().mockReturnThis(), | |
send: jest.fn().mockReturnThis(), | |
set: jest.fn().mockReturnThis(), | |
retry: jest.fn().mockReturnThis(), | |
then: cb => | |
new Promise((resolve, reject) => { | |
if (typeof responseBodiesIndex !== 'undefined') { | |
responseBodiesIndex += 1; | |
mockResponse.body = mockResponseBodies[responseBodiesIndex]; | |
} | |
if (mockError) { | |
reject(mockError); | |
} else { | |
resolve(cb(mockResponse)); | |
} | |
}), | |
timeout: jest.fn().mockReturnThis(), | |
type: jest.fn().mockReturnThis(), | |
}; | |
export default Request; |
updated, thanks @Bazze
Can someone show an example of a Jest test using this mock-up? Especially a test when the superagent call is not being performed in the test itself, but in a function called by the test.
Example:
test('demo', async () => {
await functionThatUsesSuperagent();
});
Bonus: Doing the test in Typescript 😊
there is a typo on line 1.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
We could also add for retry function: