Skip to content

Instantly share code, notes, and snippets.

@alex-quiterio
Last active February 18, 2025 08:29
Show Gist options
  • Select an option

  • Save alex-quiterio/91c9f8daba514e8152012784f5b3ccc6 to your computer and use it in GitHub Desktop.

Select an option

Save alex-quiterio/91c9f8daba514e8152012784f5b3ccc6 to your computer and use it in GitHub Desktop.
A generic mocking util function for your tests
type UnmockableTypes =
| Number
| Boolean
| String
| Symbol
| BigInt
| Date
| RegExp
| Generator;
type MockObject<T> = {
[K in keyof T]?: MockOverrides<T[K]>;
};
type MockOverrides<T> = T extends UnmockableTypes
? T
: T extends Array<infer ItemType>
? MockOverrides<ItemType>[]
: T extends InstanceType<any>
? T | MockObject<T>
: T extends (...args: infer Args) => infer ReturnType
? PossiblyMockedFn<Args, ReturnType>
: T extends object
? MockObject<T>
: never;
type PossiblyMockedFn<A extends any[], R> =
| ((...args: A) => R)
| jest.Mock<R, A>;
export function createMock<T extends object>(overrides?: MockOverrides<T>): T {
return (overrides || {}) as T;
}
export function createMockList<T extends object>(
count: number,
mapFn?: (index: number) => MockOverrides<T>,
): T[] {
if (!mapFn) {
return Array.from({ length: count }, () => createMock<T>());
}
return Array.from({ length: count }, (_, idx) => createMock<T>(mapFn(idx)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment