Here is a simple function that mocks a fake request with a random delay between 500ms and 2000ms. This can be useful for testing asynchronous code or simulating network requests in JavaScript or TypeScript.
The idea is simple: use setTimeout to resolve a promise after a random delay. The random function generates a random number between the given range, and useFakeRequest returns a promise that resolves with the provided data after that delay.
const random = (min: number, max: number): number => Math.floor(Math.random() * (max - min) + min)
interface FakeRequestOptions {
timeout?: number
status?: number
}
interface FakeResponse<T> {
data: T
status: number
statusText: string
headers: Record<string, string>
}
function useFakeRequest<T>(data: T, options?: FakeRequestOptions): Promise<FakeResponse<T>> {
const { timeout = random(500, 2000), status = 200 } = options || {}
const statusText = status === 200 ? 'OK' : 'Internal Server Error'
return new Promise((resolve) => {
setTimeout(() => {
const fakeResponse: FakeResponse<T> = {
data,
status,
statusText,
headers: {
'Content-Type': 'application/json',
},
}
return resolve(fakeResponse)
}, timeout)
})
}