问题
I am new to testing and using Enzyme and Jest to write very simple tests. I just want to check whether the component renders or not. However, (I guess) because my component uses useContext
hook, test case automatically returns undefined for all values come from the Context.
In component:
const { count, setCount } = useContext(Context);
Test case:
it('should render', () => {
const component = shallow(<MyComponent />);
const wrapper = component.find('myClassName');
expect(wrapper.length).toBe(1);
});
Test Result: Cannot read property 'count' of undefined. I don't know what I am doing wrong. Is there a simple way that always works with useContext
and other hooks to test simple things?
回答1:
I think the problem here is that when you shallow rendering a component, Context
will be ignored. So try mounting your component instead of shallow rendering it like so:
import { mount } from "enzyme"; // mount instead of `shallow` here
...
it('should render', () => {
const component = mount(<MyComponent />); // `mount` here as well
const wrapper = component.find('myClassName');
expect(wrapper.length).toBe(1);
});
来源:https://stackoverflow.com/questions/59331896/usecontext-values-return-undefined-in-testing