Skip to content

Instantly share code, notes, and snippets.

@nathggns
Last active September 22, 2018 13:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathggns/23303b8ffdfd83cf843606d2755ec32d to your computer and use it in GitHub Desktop.
Save nathggns/23303b8ffdfd83cf843606d2755ec32d to your computer and use it in GitHub Desktop.
type JestFNs<T> = { [P in keyof T]: jest.MockInstance<any> };
type Mocked<T> = JestFNs<T> & { reset(): void };
export type Mock<T> = T & { mock: Mocked<T> };
export default function mock<T extends any>(
inst: Partial<T> = {} as any
): Mock<T> {
const target = {} as any;
const proxy = new Proxy(target, {
get(target: any, key: string) {
if (key === 'then' && !inst[key]) {
return;
}
return (
target[key] ||
(target[key] = ['function', 'undefined'].includes(typeof inst[key])
? jest.fn(inst[key])
: inst[key])
);
},
}) as Mock<T>;
target.mock = proxy;
target.mock.reset = () =>
Object.values(target as JestFNs<T>).forEach(
fn => fn.mockReset && fn.mockReset()
);
return proxy;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment