Skip to content

Instantly share code, notes, and snippets.

@brunocarvalhodearaujo
Last active January 3, 2019 11:34
Show Gist options
  • Save brunocarvalhodearaujo/9cedb57fc75642086a3cfa214d2f65f8 to your computer and use it in GitHub Desktop.
Save brunocarvalhodearaujo/9cedb57fc75642086a3cfa214d2f65f8 to your computer and use it in GitHub Desktop.
/**
* @typedef {(input: RequestInfo, init: RequestInit) => Promise<Response>} Request
* @typedef {{ method: string, path: string, handler: Request, description?: string }} FakeRequest
*/
/**
* @type {FakeRequest[]}
*/
export const REQUESTS = [
{
method: 'GET',
path: '/api/user',
handler: (input, options) => Promise.resolve({
status: 200,
ok: true,
json: () => Promise.resolve([])
})
}
]
/**
* simulate requests from remote api
*
* @param {FakeRequest[]} requests
*/
export function configure (requests = []) {
const realFetch = window.fetch
/**
* override native fetch
*
* @param {RequestInfo} url
* @param {RequestInit} [opts]
* @returns {Promise<Response>}
*/
window.fetch = (url, opts = { method: 'GET' }) => {
/**
* mock request
*/
const fake = requests.find(value =>
value.method.toUpperCase() === opts.method.toUpperCase() &&
url.startsWith(value.path)
)
if (!fake) {
return realFetch(url, opts)
}
if ('description' in fake) {
console.log(`> [${fake.method}] ${fake.path}: ${fake.description}`)
}
return fake.handler(url, opts)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment