reactjstestingreact-hooksreact-testing-library

Issues with useContext when testing in React


im trying to do some testing on some of my react components. Its been mostly successful but I keep getting errors in some of my components with the useContext hook. Im trying to run a test on a Search component that isnt using the hook but the parent component is where the context is created and its used in the Search components child.

I've tried defining the context in the test file but im not sure if thats the real issue or if its something else.

I'll post the components in order, the failing test file and then the full error if there is room.

Main

import React from 'react';
import Body from './day8-weather4-body';
import Search from './day8-weather2-search';
export const CityContext = React.createContext();

export default function Main() {
    const[cityObj, setCityObj] = React.useState('Calgary');
    return (
        <div className="container p-5 bg-primary">
            <i className='text-danger fw-bold'>Main component</i>
            <h2 className='m-3'>My React Weather Application</h2>
            <CityContext.Provider value={{cityObj, setCityObj }}>
            <Search />          
            <Body />
            </CityContext.Provider>
        </div>
    );
}

Search

import React from 'react';
import Select from './day8-weather3-select';
export default function Search(props) {
    const [searchTerm, setSearchTerm] = React.useState('');
    const [cityArray, setCityArray] = React.useState([]);
    const [cel, setCel] = React.useState(null);
    const Weather_API_key = '55c5392db030dbb75249aa1ff9b8a871';
    const url = 'http://api.openweathermap.org/geo/1.0/direct';

    const handleChange = (event) => {
        setSearchTerm(event.target.value);
    }
    const handleSubmit = (event) => {
        setCel(() => (searchTerm - 32) / 1.8);
        event.preventDefault(); // Prevent default form submission behavior 
        fetch(`${url}?q=${searchTerm}&limit=3&appid=${Weather_API_key}&units=metric`)
            .then(response => response.json())
            .then(data => {
                setCityArray(data);
            });
    }
    return (
        <div className="container p-3 bg-success">
            <i className='text-danger fw-bold'>Search component</i>
            <form onSubmit={handleSubmit} className='my-3 row g-3'>
                <label className="col-sm-4 col-form-label">
                    Please enter city name:
                </label>
                <div className="col-sm-4">
                    <input data-testid= 'subSearch' type="text" value={searchTerm}
                        onChange={handleChange} className="form-control" />
                </div>
                <div className="col-sm-4">
                    <input type="submit" value="Search" className="btn btn-primary mb-3" />
                </div>
            </form>
            
            <Select cityArray={cityArray}/>

        </div>
    );
};

Select

import React from 'react';
import { CityContext } from './day8-weather1-main';
export default function Select(props) {
    const [userInput, setUserInput] = React.useState('');
    const [selectedValue, setSelectedValue] = React.useState(null);
    const { cityObj, setCityObj } = React.useContext(CityContext);
    

    const handleChange = (event) => {
        // Get the input from the user and save it in a state variable
        // event.target is the input element
        setCityObj(event.target.value);
        console.log("event.target.value" + event.target.value);

    }

    const handleSubmit = (event) => {
        console.log('The form submitted with input: ' + selectedValue);
        event.preventDefault(); // Prevent default form submission behavior 
        
    }

    return (
        <div className="container p-3 bg-warning">
            <i className='text-danger fw-bold'>Select component</i>
            <form className=' row g-3'>
                <label className="col-sm col-form-label">
                    Choose your country:</label>
                <select value={cityObj} onChange={handleChange}
                    className='form-select col-md'>
                   {props.cityArray.map((city, index) =>
                        <option onClick={handleSubmit} key={city.name + index} value={`${city.name} , ${city.state} ,  ${city.country}`}>
                            {city.name}, {city.country}</option>
                    )}
                </select>
                <div className="col-sm col-form-label">
                </div>
            </form>

            {
                selectedValue &&
                <div> You selected {selectedValue}</div>
            }
            
        </div>
    );
}

Failing test file

import React from 'react'
import { render, fireEvent, waitFor, screen } from '@testing-library/react'
import '@testing-library/jest-dom'
import Search from './day8-weather2-search'

test('search tests', async () => {
    render(<Search />)
});

Error Message

 Error: Uncaught [TypeError: Cannot destructure property 'cityObj' of '_react.default.useContext(...)' as it is undefined.]

Solution

  • You are rendering and testing the <Search/> component, not the <Main/> component. There is no context provider for <Search/> component.

    So you should wrap the <Search/> component with a <CityContext.Provider/> component when calling the render() function. You can create a <CityContext.Provider/> component for testing purpose.

    e.g.(I removed irrelevant code to demonstrate the problem)

    day8-weather2-search.jsx:

    import React from 'react';
    import Select from './day8-weather3-select';
    
    export default function Search() {
      return <Select />;
    }
    

    day8-weather3-select.jsx:

    import React from 'react';
    import { CityContext } from './day8-weather1-main';
    
    export default function Select() {
      const { cityObj, setCityObj } = React.useContext(CityContext);
      console.log('🚀 ~ Select ~ cityObj:', cityObj, setCityObj);
    
      return null;
    }
    

    day8-weather2-search.test.jsx:

    import React from 'react';
    import { render } from '@testing-library/react';
    import '@testing-library/jest-dom';
    import Search from './day8-weather2-search';
    
    import { CityContext } from './day8-weather1-main';
    
    test('search tests', async () => {
      const CityContextProvider = ({ children }) => {
        const [cityObj, setCityObj] = React.useState('test city');
        return <CityContext.Provider value={{ cityObj, setCityObj }}>{children}</CityContext.Provider>;
      };
      render(<Search />, { wrapper: ({ children }) => <CityContextProvider>{children}</CityContextProvider> });
    });
    

    Test result:

      console.log
        🚀 ~ Select ~ cityObj: test city [Function: bound dispatchSetState]
    
          at log (stackoverflow/78665137/day8-weather3-select.tsx:6:11)
    
     PASS  stackoverflow/78665137/day8-weather2-search.test.tsx
      √ search tests (25 ms)                                                                                                                                                                                                                             
                                                                                                                                                                                                                                                         
    Test Suites: 1 passed, 1 total                                                                                                                                                                                                                       
    Tests:       1 passed, 1 total                                                                                                                                                                                                                       
    Snapshots:   0 total
    Time:        1.196 s, estimated 14 s
    Ran all test suites related to changed files.