When using jest-mock-extended
to create a mock like this:
export interface SomeClient {
someFunction(): number;
someOtherFunction(): number;
}
const mockClient = mock<SomeClient>();
mockClient.someFunction.mockImplementation(() => 1);
The default behavior of functions on the mock is to return undefined
if no explicit implementation is provided. For example, calling someFunction
will return 1 as expected, but calling someOtherFunction
without an implementation will result in undefined.
mockClient.someFunction(); // returns 1
mockClient.someOtherFunction(); // returns undefined
This can lead to unexpected errors in tests, especially with TypeScript where undefined values may not match expected types. To address this issue, one approach is to provide a default implementation for all functions that throws an error when called:
const mockClient = mock<SomeClient>({
someFunction: jest.fn().mockImplementation(() => {
throw new Error('someFunction not mocked');
}),
someOtherFunction: jest.fn().mockImplementation(() => {
throw new Error('someOtherFunction not mocked');
}),
});
However, maintaining this approach becomes cumbersome with multiple functions and requires updating when new functions are added. Is there a simpler way to apply a default mock implementation to all functions in jest?