Skip to content

Instantly share code, notes, and snippets.

@mpontus
Created August 7, 2020 15:24
Show Gist options
  • Select an option

  • Save mpontus/ccc3570e7688cceb8404f7b31a239d6c to your computer and use it in GitHub Desktop.

Select an option

Save mpontus/ccc3570e7688cceb8404f7b31a239d6c to your computer and use it in GitHub Desktop.
Jest class mock
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