Skip to content

Instantly share code, notes, and snippets.

@lot224
Last active December 20, 2021 20:42
Show Gist options
  • Save lot224/cd1f13ba09775d0ed016c6cf821be027 to your computer and use it in GitHub Desktop.
Save lot224/cd1f13ba09775d0ed016c6cf821be027 to your computer and use it in GitHub Desktop.
mockFetch - require in setup.js
export const hookFetch = global.fetch;
type collection = {
[key: string]: {
response: {
success?: unknown
error?: unknown
}
headers?: {
[key: string]: string
},
resolve?: boolean,
duration?: number
}
};
let mockCollection: collection = {};
export const mockFetchClear = (url?: string) => {
if (url === undefined) {
mockCollection = {};
} else if (mockCollection[url] !== undefined) {
const newCollection: collection = {};
for (const [key, value] of Object.entries(mockCollection)) {
if (key !== url)
newCollection[key] = value;
};
mockCollection = newCollection;
}
}
export const mockFetch = (
url: string,
response: {
success?: unknown
error?: unknown
},
headers?: { [key: string]: string },
resolve?: boolean,
duration?: number
) => {
mockCollection[url] = { response, headers, resolve, duration};
global.fetch = jest.fn().mockImplementation((url, request) => {
const mock = mockCollection[url];
if (!mock)
// Need to call mockFetch for specified url so we can mock the response.
throw new Error(`No mock URL Specified for ${url}`);
const _headers = mock.headers || {};
const _resolve = mock.resolve === false ? false : true;
const _duration = mock.duration ? mock.duration : 50;
if (_headers["content-type"] === undefined)
_headers["content-type"] = "application/json";
const response = {
"__MOCK_REQUEST__": request,
statusText: _resolve === true ? "OK" : "Internal Server Error",
status: _resolve === true ? 200 : 500,
ok: _resolve,
url: url,
redirected: false,
headers: {
append: jest.fn(),
delete: jest.fn(),
forEach: (callback: Function, thisArg?: any): void => {
// Something about only showing custom or the following specified keys
// https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types
// const keys = ["Cache-Control", "Content-Language", "Content-Type", "Expires", "Last-Modified", "Pragma"];
// keys.forEach(key => { callback.apply(key, _headers[key]); });
// Using Basic as a type allows for all headers to be visible.
Object.keys(_headers).forEach(header => {
callback.apply(header, _headers[header]);
});
},
get: (name: string): string | null => {
return _headers[name] ? _headers[name] : null;
},
has: (name: string): boolean => {
return _headers[name] ? true : false;
},
set: jest.fn(),
},
json: () => Promise.resolve(JSON.parse(JSON.stringify(mockCollection[url].response))),
text: () => Promise.resolve(JSON.stringify(mockCollection[url].response)),
type: "basic"
};
return new Promise((resolve, reject) => {
const result = _resolve === true ? resolve : reject
setTimeout(() => {
result(response);
}, _duration);
});
})
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment