1

I tried using react-hooks-testing-library but it dosn't seem how handle hooks that use useContext.

import React,{useContext} from 'react'
import {AuthContextData} from '../../AuthContext/AuthContext'
const useAuthContext = () => {
    const {authState} = useContext(AuthContextData) 
    const {isAuth,token,userId,userData} = authState
    return {isAuth,token,userId,userData}
  }
  export default useAuthContext
Michael Peyper
  • 6,814
  • 2
  • 27
  • 44
Ktr1000
  • 253
  • 5
  • 17
  • Does this answer your question? [Testing a custom hook with renderHook](https://stackoverflow.com/questions/59442450/testing-a-custom-hook-with-renderhook) – Liam May 23 '23 at 18:41

2 Answers2

3

You have to wrap your hook in a context provider:

let authContext
renderHook(() => (authContext = useAuthContext()), {
  wrapper: ({ children }) => (
    <AuthContextData.Provider value={/* Your value */}>
      {children}
    <AuthContextData.Provider>
  )
})
Gio Polvara
  • 23,416
  • 10
  • 66
  • 62
-1

Let's say you have a component where you call the useContext(context) hook to get a key isLoading that should be false or true.

If you want to test useContext in a component you could test it as follow:

const context = jest.spyOn(React, 'useContext');

if each test in the same file need to have different context values, then inside your test, you can mock the implementation like this:

context.mockImplementationOnce(() => {
    return { isLoading: false };
  });

or outside the tests for all tests to have same context:

context.mockImplementation(() => {
    return { isLoading: false };
  });

Hope it helps.

  • Redux explicitly say [*Do not try to mock selector functions or the React-Redux hooks!*](https://redux.js.org/usage/writing-tests#guiding-principles) – Liam May 23 '23 at 18:43
  • But this is not redux, this is react. Although I believe the accepted answer is a best approach, this is valid as well. – Nacho H Aug 01 '23 at 20:43