Answer the question
In order to leave comments, you need to log in
How to test a function (jest) that returns React.useContext?
export const context = React.createContext(null);
export function useErrorNot() {
const showNot = React.useContext(context);
const defaultText = 'error';
if (!showNot) {
throw new Error('error');
}
return (text = defaultText) => {
showNotification({ text });
};
}
test('check fn', () => {
const mockUseContext = jest.fn().mockImplementation(() => ({}));
React.useContext = mockUseContext;
const mockFn = jest.fn(() => useErrorNotification())
expect(mockFn()).toHaveBeenCalled();
})
Answer the question
In order to leave comments, you need to log in
https://react-hooks-testing-library.com/reference/api
renderHook
The first parameter is your "function" (custom hook), the second parameter is the options where you need to specify the wrapper component containing the provider with the context (perhaps the the provider will be a wrapper, and the context is passed through initialProps, but I haven't tried that)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question