-
-
Save markuso/f7c59cf152f52c7a50eae5e3e6a56bb4 to your computer and use it in GitHub Desktop.
Jest superagent mock
This file contains hidden or 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
| '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