A
A
al_542021-08-27 09:32:51
React
al_54, 2021-08-27 09:32:51

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 });
  };
}


 How can you test this feature?
My attempts:
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

1 answer(s)
A
Alexandroppolus, 2021-08-27
@al_54

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 question

Ask a Question

731 491 924 answers to any question