I am trying to set up tests for my component App.js
that takes in a context
as a prop and returns a provider. The issue is when I am trying to test it, the context that I pass into it always resolves to undefined.
I put a console log in the component and and one between creating the context and creating the Component (which should receive context as a param). This resulted in the console.log in the component first for some reason. This is probably why I am getting context is undefined as it hasn't been initialized yet.
// Component/Provider
const App = (props) => {
const {children, context} = props;
const {data, dispatch} = useReducer(reducer);
console.log(context); //undefined and this console.log runs first
return <context.Provider value={useCallback(dispatch)}>{children}</context.Provider>
}
In my test.js
import React, {useContext} from 'react';
import {render} from 'react-testing-library';
import {App} from './App';
const context = React.createContext();
function Provider(children) {
console.log(context); //Is correct but runs second
return <App Context={context}>{children}</App>;
}
const customRender = (ui, options) =>
render(ui, { wrapper: Provider, ...options });
const Consumer = () => {
const dispatch = useContext(context);
returns <Button onClick={dispatch({type: 'Do something'})}>Whatever</Button/>;
}
customRender(<Consumer />)
I should be able to pass a Context
into my component to create the provider but its always undefined.
context
prop butContext
is passed. casing matters. – Starshaped