Created
August 7, 2020 15:24
-
-
Save mpontus/ccc3570e7688cceb8404f7b31a239d6c to your computer and use it in GitHub Desktop.
Jest class mock
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 JestMock<T extends (...args: any[]) => any> = jest.Mock< | |
| ReturnType<T>, | |
| Parameters<T> | |
| >; | |
| export type InstanceMock<T> = T & | |
| { | |
| [K in keyof T]: T[K] extends (...args: any[]) => any ? JestMock<T[K]> : T[K] | |
| }; | |
| type Class<T> = new (...args: any[]) => T; | |
| const initializeMethod = (prop: any, instance?: any): any => { | |
| if (!instance || !instance[prop]) { | |
| return jest.fn(() => { | |
| throw new Error(`Implementation for ${prop} is not provided`); | |
| }); | |
| } | |
| const orig = instance[prop]; | |
| return typeof orig === "function" ? jest.fn(orig.bind(instance)) : orig; | |
| }; | |
| /** | |
| * Mock gives class or interface using jest mocks | |
| */ | |
| export function mock<T>(instance?: Partial<T>): InstanceMock<T> { | |
| return new Proxy( | |
| {}, | |
| { | |
| get: (target: Partial<InstanceMock<T>>, prop: keyof T) => { | |
| if (!target[prop]) { | |
| target[prop] = initializeMethod(prop, instance); | |
| } | |
| return target[prop]; | |
| } | |
| } | |
| ) as InstanceMock<T>; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment