Skip to content

Instantly share code, notes, and snippets.

@danmakenoise
Last active February 29, 2024 20:23
Show Gist options
  • Star 43 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save danmakenoise/c503854508f80137fe547943218ccc05 to your computer and use it in GitHub Desktop.
Save danmakenoise/c503854508f80137fe547943218ccc05 to your computer and use it in GitHub Desktop.
Unit Testing Children of React Context API Consumers with Enzyme
// Component.js
const Component = props => (
<MyContext.Consumer>
{(context) => (
<Foo
bar={props.bar}
baz={context.baz}
/>
)}
</MyContext.Consumer>
);
// Component.test.js
const outer = shallow(<Component bar="bar" />);
const Children = outer.props().children;
const wrapper = shallow(<Children baz="baz" />);
expect(wrapper.find(Foo)).toHaveLength(1);
expect(wrapper.find(Foo)).props().bar).toBe('bar');
expect(wrapper.find(Foo)).props().baz).toBe('baz');
@ardwalker
Copy link

Thanks for posting, very helpful!

@jktravis
Copy link

Man, I wish I could give more than one star. Thanks!

@mdodge1982
Copy link

So simple, I love it. Thank you!

@lauronascimento-hotmart

Solved my problem, thank you a lot!

@wendelnascimento
Copy link

Really nice, now I can continue using my snapshots in components with Context.Consumer!

@royledford
Copy link

Awesome solution! Found this after an hour of trying to figure out how to handle some tests and works great.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment