Skip to content

Instantly share code, notes, and snippets.

@fabienjuif
Last active May 17, 2022 07:14
Show Gist options
  • Select an option

  • Save fabienjuif/57b4d9ac413fd864ef219d0b70732324 to your computer and use it in GitHub Desktop.

Select an option

Save fabienjuif/57b4d9ac413fd864ef219d0b70732324 to your computer and use it in GitHub Desktop.
jest / typescript / mock class prototype

What

You can use this helper to mock AND types your class methods.

Example

class A {
  foo(a: number, b: number): number { return a + b }
}

const a = mockClass(A.prototype)
a.foo.mockReturnValueOnce(32)
export const mockClass = <T>(prototype: T) => {
const descriptors = Object.getOwnPropertyDescriptors(prototype);
const mockedVersion = Object.fromEntries(
Object.entries(descriptors).map(([key, { value }]) => [key, typeof value === 'function' ? jest.fn() : value]),
);
return jest.mocked<T>(mockedVersion as T);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment