Last active
January 3, 2019 11:34
-
-
Save brunocarvalhodearaujo/9cedb57fc75642086a3cfa214d2f65f8 to your computer and use it in GitHub Desktop.
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
/** | |
* @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