Skip to content

Instantly share code, notes, and snippets.

@IlCallo
Created January 23, 2023 12:47
Show Gist options
  • Save IlCallo/5efbab4b6d88e601c629273e3b80a032 to your computer and use it in GitHub Desktop.
Save IlCallo/5efbab4b6d88e601c629273e3b80a032 to your computer and use it in GitHub Desktop.
An helper to mock Axios requests while prototyping
import { AxiosResponse } from 'axios';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const createResponseStub: <T = any>(data?: T) => AxiosResponse = (data) => ({
config: {},
data,
status: 200,
statusText: '',
headers: {},
});
/**
* Simulate an asyncronous request to the server and provide an Axios-compatible response.
* It allows you to write services for backend endpoints not ready yet.
* When the actual endpoint is ready, you can then just swap the mockRequest
* with the axios request and the nearby code won't have to change.
*
* @param options Define the returned data and/or timeout of the stub
* @returns A successful axios response
*
* @example
* const { data } = await mockRequest({ data: { id: 123, name: 'Test' } });
* // Later on you can swap it with an axios request
* const { data } = await webApi.get(`formulas/${formulaId}`);
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function mockRequest<T = any>(options: { data?: T; timeout?: number }) {
return new Promise<AxiosResponse<T>>((resolve) =>
setTimeout(
() => resolve(createResponseStub(options.data)),
options.timeout ?? 2000
)
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment