I am trying to create a simple snapshot test of a component that implements useContext. I have wrapped the component with the ContextProvider but I am still getting the following error:
TypeError: Cannot read properties of null (reading ‘useContext’)
Here is the code for the test case:
describe('Testing Incoming Shipments Snapshot', () => {
test('Test incoming shipments table renders', async () => {
const shipments: ShipmentType[] = TestShipments;
const isLoading = false;
const currentVehicle: VehicleType = vehicle;
const setCurrentVehicle = () => {
//do nothing
};
const currentShipment: ShipmentType = testShipment;
const setCurrentShipment = () => {
//do nothing
};
const setShipments = () => {
//do nothing
};
const setIsLoading = () => {
//do nothing
};
const sortDirection = '';
const setSortDirection = () => {
//do nothing
};
const sortColumn = '';
const setSortColumn = () => {
//do nothing
};
const step = [''];
const setStep = (newStep: string[]) => [];
const defaultShipmentContextValues = {
shipments,
setShipments,
isLoading,
setIsLoading,
sortDirection,
setSortDirection,
sortColumn,
setSortColumn,
currentVehicle,
setCurrentVehicle,
currentShipment,
setCurrentShipment,
};
const component = render(
<StepContext.Provider value={{ step, setStep }}>
<ShipmentContext.Provider value={defaultShipmentContextValues}>
<IncomingShipments shipments={shipments} />
</ShipmentContext.Provider>
</StepContext.Provider>
);
expect(component).toMatchSnapshot();
});
});
The IncomingShipments component does not use context but a sub-component (ShipmentCard) does so here is the code for that sub-component:
import React, { useState, useContext } from 'react';
import ShipmentContext from '../../contexts/ShipmentContext';
import StepContext from '../../contexts/StepContext';
const ShipmentCard = ({ shipment, view }: Props) => {
const { step, setStep } = useContext(StepContext);
const { setCurrentShipment } = useContext(ShipmentContext);
I opted to show just the code that is failing because it’s a large component. But The component works perfectly fine, it’s been run and tested by several people but for whatever reason Jest throws the above error. And yes I am importing the contexts in this component I
I’ve made sure I am using up to date npm packages, and I’ve also made sure that Jest itself is working by writing other snapshot test for components that do not have any use hooks in them but for whatever reason Jest just does not like any component with any kind of use hook.
The Bunz is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.