I'm new to React Hooks and what I'm trying to achieve is to test a React component (called CardFooter) that contains a call to useEffect hook that gets triggered a global context variable is modified.
CardFooter.js:
const CardFooter = props => {
const [localState, setLocalState] = useState({
attachmentError: false
});
const globalContext = useContext(GlobalContext);
React.useEffect(()=> {
setLocalState({
...localState,
attachmentError: globalContext.data.attachmentError
});
},[globalContext.data.attachmentError]);
}
CardFooter.test.js:
import Enzyme, { shallow } from 'enzyme';
Enzyme.configure({ adapter: new Adapter() });
describe('<CardFooter />', () => {
let useEffect;
const mockUseEffect = () => {
useEffect.mockImplementation(f => f());
};
useEffect = jest.spyOn(React, "useEffect");
mockUseEffect(); //
it('should render correctly with no props.', () => {
}
const mockUseEffect = () => {
useEffect.mockImplementation(f => f());
};
useEffect = jest.spyOn(React, "useEffect");
mockUseEffect();
const wrapper = shallow(<CardFooter />);
expect(toJson(wrapper)).toMatchSnapshot();
});
the error that I'm getting when running the test is:
TypeError: Cannot read property 'attachmentError' of undefined
I tried the approach presented here: https://medium.com/@pylnata/testing-react-functional-component-using-hooks-useeffect-usedispatch-and-useselector-in-shallow-9cfbc74f62fb . However it seems that shallow does not pick the mocked useEffect implementation. I also tried mocking the useContext and the globalContext.data.attachmentError. Nothing seems to work.
const useEffect = jest.spyOn(React, "useEffect").mockImplementation(() => {})
just beforedescribe()
. – Albert Alises