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;
-
Can you show what your test looks like?juliomalves– juliomalves2021年03月31日 18:52:06 +00:00Commented Mar 31, 2021 at 18:52
1 Answer 1
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.
Comments
Explore related questions
See similar questions with these tags.