1
votes

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
u got this fixed? im having same issuesuisied
Did you provide a default value for your context when you created it via createContext?bensampaio
@bensampaio I did, still undefinedJason G

1 Answers

0
votes

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);
});