Skip to content

Instantly share code, notes, and snippets.

@aholachek
Last active April 7, 2020 18:29
Show Gist options
  • Save aholachek/facbc486bd98afe2060784876881fe71 to your computer and use it in GitHub Desktop.
Save aholachek/facbc486bd98afe2060784876881fe71 to your computer and use it in GitHub Desktop.
mockFetch function for jest
export type FetchConfig = RequestInit & {
postman?: boolean;
method?: keyof typeof HTTPMethods;
body?: any;
root: string;
path?: string;
params?: Record<string, any>;
};
export interface Global {
document: Document;
window: Window;
fetch: (url: string, config: any) => Promise<any>;
}
declare const global: Global;
type OnFetch = (request: RequestInit) => Promise<any>;
export const unmockFetch = () => {
// @ts-ignore
if (global.fetch && global.fetch.mockRestore) global.fetch.mockRestore();
};
export const mockFetch = (onFetch: OnFetch) => {
unmockFetch();
const mockFetch = async (url: string, config: FetchConfig) => {
let parsedBody;
try {
parsedBody = JSON.parse(config.body);
} catch (e) {}
try {
const json = await onFetch({
...new Request(url, config),
// a slightly hacky convenience
// to offer access to the body object, if it exists
body: parsedBody
});
return Promise.resolve({
ok: true,
json() {
return json;
}
});
} catch (e) {
return Promise.resolve({
ok: false,
json() {
return e;
}
});
}
};
jest.spyOn(global, "fetch").mockImplementation(mockFetch);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment