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.
Idea is simple, we are using setTimeout
to resolve a promise after a random delay. The random
function generates a random number between the given range and the useFakeRequest
function returns a promise that resolves with the provided data after the random delay.
const random = (min, max) => 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)
})
}