Last active
September 22, 2018 13:52
-
-
Save nathggns/23303b8ffdfd83cf843606d2755ec32d 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
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