Let's say we have a custom hook named useUser
const useUser = (): IUser => useContext(MiniAppContext).user;
Then it is used in another component
import { useUser } from '@ABC'
const { monitoring } = useUser(); // please note that monitoring is an object having property id
When we run test case, it shows
TypeError: xxxx.useUser is not a function
I used below codes to pass the unit test, but I know that this is good enough. Please let me know what the best practise for this. Thanks in advance.
Update:
jest.mock('@ABC', () => ({
userUser: () => ({monitoring: {}} as IUser)
}));
CodePudding user response:
An idea would be to create a util function that mocks the custom hook:
import * as useUserHook from '@ABC';
function generateUseUserHook(mock?: IUser): IUser {
const value: IUser = {
monitoring: jest.fn(),
// mock return value (you can use faker)
...mock
};
jest.spyOn(useUserHook, 'useUser').mockReturnValue(value);
return value;
}
instead of jest.mock
.