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?


    TypeError: Cannot read property 'setUser' of undefined

      25 |           const { isAuthenticated, user } = data;
      26 |           if (isAuthenticated) {
    > 27 |             authContext.setUser(user);


    test('user input correct login information', () => {
        const { getByTestId, getByText } = render(<LoginForm />);
        const resInfo = {username: 'Bpun1p'}
        const resp = {isAuthenticated: true, user: resInfo}

        fireEvent.change(getByTestId('Username'), {target: {value: "Bpun1p"}})
        fireEvent.change(getByTestId('Password'), {target: {value: "Guy123su"}})'LoginBtn'));


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, []: });

  const onSubmit = (event) => {
    if (username.username !== '') {
        .then((data) => {
          const { isAuthenticated, user } = data;
          if (isAuthenticated) {
          } 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:


    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?