Skip to content

Instantly share code, notes, and snippets.

@madbence
Last active June 16, 2021 15:37
Show Gist options
  • Save madbence/bc3862c402285b48abe56958a64bb13f to your computer and use it in GitHub Desktop.
Save madbence/bc3862c402285b48abe56958a64bb13f to your computer and use it in GitHub Desktop.
function createMock<T>(mock: Partial<jest.Mocked<T> | T> = {}) {
const props: any = {};
const p: any = new Proxy({}, {
get(_target, prop) {
if (prop in mock) return (mock as any)[prop];
if (prop in props) return props[prop];
if (prop === Symbol.iterator) return undefined;
if (prop === 'then') return undefined;
if (prop === '_isMockFunction') return false;
const fn: any = jest.fn(() => createMock());
props[prop] = fn;
return fn;
},
set(_target, prop, value) {
props[prop] = value;
return true;
},
});
return p as jest.Mocked<T>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment