3

Hope you all doing well under the circumstances :) I'm a having an error in useContext when running the render test in a React app, in the App component.

  • Here's the context api:

    const { userId } = useContext(UserContext);

  • Here's the error:

    TypeError: Cannot destructure property 'userId' of '(0 , _react.useContext)(...)' as it is undefined.

    35 | const { userId } = useContext(UserContext);

The object is undefined in the beginning because it's an API call to get userId. Once logged in, the userId is available. So when running in development, it works perfectly, but when running tests, it shows this error.

  • Finally here's the UserContext component:

    export const UserContext = createContext();

     const UserProvider = ({ children }) => {
     const [userId, setUserId] = useState("");
     const getUserId = async () => {
     if (token) {
     await axios
     .get(`${baseURL}/auth/user`, {
     headers: {
     authorization: token
     }
     })
     .then(function (response) {
     const { data } = response;
     return setUserId(data.userId);
     })
     .catch(function (err) {
     if (err.response)
     return toast.error(
     <div>
     <InfoIcon style={{ marginBottom: "6px" }} />
     <p>
     getUserId - {err.response.status} - {err.response.message}
     </p>
     </div>
     );
     return toast.error(
     <div>
     <InfoIcon style={{ marginBottom: "6px" }} />
     <p>User Context - CORS</p>
     </div>
     );
     });
     }
     };
     useEffect(() => {
     getUserId();
     }, []);
     return (
     <UserContext.Provider value={{ userId }}>{children}</UserContext.Provider>
     );
     };
     export default UserProvider;
    
asked Mar 29, 2021 at 15:16
1
  • Can you show what your test looks like? Commented Mar 31, 2021 at 18:52

1 Answer 1

7

I need to see your test.js file. But you should render your component wrapped with context component in your test file to avoid error if you render without it. In your case you should: render(<UserProvider><App /></UserProvider> in your test.js file.

answered May 4, 2021 at 16:35
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.