Hi I am using react functional component and I have almost covered all the test cases which works fine until I added one line if code which uses the state value from my context api provider.
MyComponent code.
The line I added
if (uploadedSuccessfullyContext) return null;
The existing function code
const fetchUserInfo = async () => {
const userInfo = await getUserInfo();
setEnterpriseId(userInfo.enterpriseId);
setFirstName(userInfo.firstName);
setIsLoading(false)
};
return (
<>rest of the component jsx<>
)
My test cases
jest.mock("react", () => ({
...jest.requireActual("react"),
useContext: jest.fn()
}));
const mockContextValue = {
uploadedSuccessfullyContext: false
};
beforeEach(() => {
setEnterpriseIdMock = jest.fn();
setFirstNameMock = jest.fn();
useContext.mockReturnValue(mockContextValue);
});
it("should get userInfo and call axios api correctly with no data", async () => {
let wrapper;
const mockUserInfo = {
enterpriseId: "mockEnterpriseId",
firstName: "mockFirstName"
};
getUserInfo.mockResolvedValue(mockUserInfo);
const mockResponse = { data: [] };
axios.get.mockImplementationOnce(() => Promise.resolve(mockResponse));
await act(async () => {
wrapper = mount(
<DocumentHistory
setEnterpriseId={setEnterpriseIdMock}
setFirstName={setFirstNameMock}
/>
);
});
expect(getUserInfo).toHaveBeenCalled();
wrapper.update();
expect(axios.get).toHaveBeenCalled();
expect(axios.get).toHaveBeenCalledTimes(1);
});
The error I am getting
TypeError: Cannot read properties of undefined (reading ‘get’)Jest
NOTE: If I remove that implementation of context api and if statement the testis passed and if add this is the error. Any idea what is missing ? your views and expertise are appreciated.