how do i run a test with jest/RTL on authcontext()

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);
  };

1 answer

  • answered 2020-11-25 01:42 IamMHC

    in Test <LoginForm/> replace with <AuthContext.Provider> <LoginForm/><AuthContext.Provider> and pass the required props for AuthContext.Provider for the run app

  • Test input without label with React Testing Library

    I use react-testing-library in my application. Normally, to check if the input is in the form, we use getByLabelText. For example:

    getByLabelText(/name/i)
    

    But what if my input does not have any label? This is because of the design (UI) so I cannot have a label for the input. How can I check if that input exists in the form?