Skip to content

Instantly share code, notes, and snippets.

@IhsanMujdeci
Last active July 8, 2021 00:37
Show Gist options
  • Save IhsanMujdeci/da5a4fdc3174d995310c5092be48d1a4 to your computer and use it in GitHub Desktop.
Save IhsanMujdeci/da5a4fdc3174d995310c5092be48d1a4 to your computer and use it in GitHub Desktop.
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