I’m trying to test that a function, which is defined inside of a hook, is called in a component that uses that hook/function. I’m familiar with mocking simple modules/functions, but this scenario has me confused as I don’t know how to mock only a single returned function from that hook without losing all of the other functions/logic in that hook, which I don’t want to mock.
Let’s say I have a hook that looks like this:
import { useState } from 'react';
export const useSomeHook = () => {
const [someValue, setSomeValue] = useState();
const [someOtherValue, setSomeOtherValue] = useState();
// a bunch of other logic in here...
return {
someValue,
setSomeValue,
someOtherValue,
setSomeOtherValue,
}
}
Then I have a function component that uses that hook:
export const SomeComponent = () => {
const { setSomeValue } = useSomeHook();
return (<button onClick={() => setSomeValue('hey')}>hello</button>);
}
I’d like to be able to test that setSomeValue
gets called when the button is clicked.
const mockSetSomeValue = jest.fn();
jest.mock('./useSomeHook.js', () => {
const actual = jest.requireActual('./useSomeHook.js');
return {
...actual,
// This won't work because now everything else inside of useSomeHook is missing and other tests I have in this file will fail
useSomeHook: () => ({
setSomeValue: mockSetSomeValue,
})
}
});
describe('SomeComponent', () => {
it('should call setSomeValue when button is clicked', () => {
render(<SomeComponent />);
// fire event to click button
expect(mockSetSomeValue).toHaveBeenCalledWith('hey');
});
});
Is something like this possible? Thanks!