Skip to content

Instantly share code, notes, and snippets.

@alshdavid
Created September 3, 2020 05:49
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 alshdavid/0624332f550d36ef0c4faa42a0203548 to your computer and use it in GitHub Desktop.
Save alshdavid/0624332f550d36ef0c4faa42a0203548 to your computer and use it in GitHub Desktop.
export type MatcherFn<T> = (actualValue: T) => boolean;
export interface CalledWithMock<T, Y extends Array<any>> extends jest.Mock<T, Y> {
calledWith: (...args: Y) => jest.Mock<T, Y>;
}
export type MockedInterface<T> = {
[K in keyof T]: T[K] extends (...args: infer A) => infer B
? CalledWithMock<B, A> & T[K]
: MockedInterface<T[K]> & T[K];
};
export const mockInterface = <T>(initialValue: any = {}): MockedInterface<T> => {
const source: any = {
toString: jest.fn(),
...initialValue,
};
const proxy: any = new Proxy(source as any, {
get(target, prop: any) {
if (!target.hasOwnProperty(prop)) {
target[prop] = jest.fn();
}
return target[prop];
},
set(target, prop: string, value: any) {
target[prop] = value;
return true;
},
});
return proxy;
};
export const initProperty = (target: any, prop: string | number | symbol) => {
target[prop] = undefined;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment