I am trying to test the process of my code when the user logs in correct information; however, i get stuck on an error that states that authContext is seen as undefined. Am i testing this correctly? How do i fix this error?
error
TypeError: Cannot read property 'setUser' of undefined
25 | const { isAuthenticated, user } = data;
26 | if (isAuthenticated) {
> 27 | authContext.setUser(user);
loginForm.test.js
test('user input correct login information', () => {
const { getByTestId, getByText } = render(<LoginForm />);
const resInfo = {username: 'Bpun1p'}
const resp = {isAuthenticated: true, user: resInfo}
AuthService.login.mockResolvedValue(resp)
fireEvent.change(getByTestId('Username'), {target: {value: "Bpun1p"}})
fireEvent.change(getByTestId('Password'), {target: {value: "Guy123su"}})
fireEvent.click(getByTestId('LoginBtn'));
});
loginForm.js
import React, { useContext, useState } from 'react';
import { useHistory } from 'react-router-dom';
import SocialSignUp from './SocialSignUp';
import { AuthContext } from '../../context/AuthContext';
import AuthService from '../../service/AuthService';
function LoginForm() {
const [username, setUsername] = useState({ username: '' });
const [isValidEntry, setValidEntry] = useState(true);
const authContext = useContext(AuthContext);
const history = useHistory();
const onChange = (event) => {
setUsername({ ...username, [event.target.name]: event.target.value });
};
const onSubmit = (event) => {
event.preventDefault();
if (username.username !== '') {
AuthService.login(username)
.then((data) => {
console.log(data);
const { isAuthenticated, user } = data;
if (isAuthenticated) {
authContext.setUser(user);
authContext.setIsAuthenticated(isAuthenticated);
history.push('/profile/global');
} else setValidEntry(false);
});
} else setValidEntry(false);
};
in Test <LoginForm/>
replace with <AuthContext.Provider> <LoginForm/><AuthContext.Provider>
and pass the required props for AuthContext.Provider for the run app