I have a test that should render a hook via renderHook, and also wrap it in a context provider:
describe("useShowMessages", () => {
const amendedMockContext = {
...baseMockContext, // baseMockContext is jut an object I've been using with a value for each item I have in context.
conversationData: {
data: [{ key: "test" }],
},
};
const MockContext = createContext(amendedMockContext);
it("should return a full visibility tree on first call", () => {
const wrapper = ({ children }: any) => (
// @ts-ignore
<MockContext.Provider value={amendedMockContext}>
{children}
</MockContext.Provider>
);
const { result } = renderHook(() => useShowMessages(), { wrapper });
console.log(result.current);
});
});
I use context in my hook like so:
export const useShowMessages = () => {
const {
conversationData: { data },
setNeedsInputIndexes,
showChat,
setCurrentStep,
} = useContext(AppContext);
// the rest of the hook logic
}
However, when I try to run this test, I always get the same error:
TypeError: Cannot read properties of undefined (reading 'data')
5 | export const useShowMessages = () => {
6 | const {
> 7 | conversationData: { data },
| ^
8 | setNeedsInputIndexes,
9 | showChat,
10 | setCurrentStep,
You can see that the test is failing where I am trying to extract context values using useContext. It is not recognising data at all.
I've set it up following the examples laid out in testing-library docs as well as the examples in this article. I have other tests using context and baseMockContext/amendedMockContext, as well as other renderHook tests. they all work fine, but this is my first that uses both in conjunction and it doesn't work...
EDIT:
Here's my AppContext for use in the actual application:
import { createContext, Dispatch, SetStateAction } from "react";
import {
ConversationDataType,
FetchResultsType,
IntroductionDataType,
} from "./types";
export type AppContextType = {
// a bunch of types
};
export const AppContext = createContext({} as AppContextType);