Last active
July 8, 2021 00:37
-
-
Save IhsanMujdeci/da5a4fdc3174d995310c5092be48d1a4 to your computer and use it in GitHub Desktop.
This file contains 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
export type MockedInterface<T> = { | |
[K in keyof T]: T[K] extends (...args: infer A) => infer B | |
? jest.Mock<B, A> | |
: MockedInterface<T[K]>; | |
}; | |
export function mockInterface<T>( | |
initialValue: { [K in keyof T]?: MockedInterface<T[K]> } = {} | |
): MockedInterface<T> { | |
const source = { | |
toString: jest.fn(), | |
// Initialise then and catch to null to avoid recursive resolution if ever awaited or promise chained | |
then: null, | |
catch: null, | |
...initialValue, | |
}; | |
const proxy = new Proxy(source, { | |
get(target: Record<string | number, unknown>, prop: string | number) { | |
if (!target.hasOwnProperty(prop)) { | |
target[prop] = jest.fn(); | |
} | |
return target[prop]; | |
} | |
}); | |
return proxy as MockedInterface<T>; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment