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

1

2 Answers 2

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>
  )
})
Sign up to request clarification or add additional context in comments.

Comments

-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.

2 Comments

But this is not redux, this is react. Although I believe the accepted answer is a best approach, this is valid as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.