'How do I fix the jest unit testing - "TypeError: Cannot read properties of undefined" on importing states from my Authcontext provider?
I am trying to write a unit test for my React components using Jest and enzyme.
My component contains some 'states' which are actually imported from an AuthContext Provider.
This my test code -
import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import Destination from "../Components/Destination"
Enzyme.configure({ adapter: new Adapter() });
describe('Destination Component', () => {
it('should add the selected Destination to the state', () => {
const planet = []
const selectDestinationInstance = shallow(<Destination/>)
const selectDOM = selectDestinationInstance.find("#demo-simple-select")
selectDOM.simulate('change', {'target' : {name : "Donlon"}})
expect(planet[0]).toequal("Donlon")
})
})
And this is the component - Destination I am testing -
import React, { useContext } from "react";
import { AuthContext } from "../Context/AuthProvider.js";
import "../css/Destination.css";
import Vehicles from "../Components/Vehicles";
import "../css/Vehicle.css"
import {
Paper,
InputLabel,
MenuItem,
FormControl,
Select,
Grid
} from "@mui/material";
function Destination() {
const {
selectedPlanets,
SetselectedPlanets,
AllPlanets,
} = useContext(AuthContext);
const OnSelectPlanet = (e, key) => {
const clonedSelectedPlanets = JSON.parse(JSON.stringify(selectedPlanets));
clonedSelectedPlanets[key] = e.target.value;
SetselectedPlanets(clonedSelectedPlanets);
};
return (
<>
<div className="Parent_Card">
<Grid container justify="center" alignItems="center">
{selectedPlanets.map((planet, index) => {
return (
<div className="PlanetsAndVehicles" key={index}>
<Grid item xs = {2} md = {6} lg = {12}>
<Paper elevation={5}>
<FormControl fullWidth key = {index}>
<InputLabel id="demo-simple-select-label">
Destination {index + 1}
</InputLabel>
<Select
labelId="demo-simple-select-label"
id="demo-simple-select"
key={index}
value={selectedPlanets[index]}
onChange={(e) => OnSelectPlanet(e, index)}
>
<MenuItem key={index} value={selectedPlanets[index]}>
{selectedPlanets[index]}
</MenuItem>
{OptionsToRender}
</Select>
<>
{selectedPlanets[index] ? (
<>
<div className="Distance_measure">
Distance - {getDistance(index)}
</div>
<Vehicles
index={index}
PlanetDistance={getDistance(index)}
/>
</>
) : (
<></>
)}
</>
</FormControl>
</Paper>
</Grid>
</div>
);
})}
</Grid>
</div>
</>
);
}
export default Destination;
The error I am getting - TypeError: Cannot read properties of undefined (reading 'selectedPlanets').
I am expecting my test to pass.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
