I have been using enzyme and love it a lot. It works with react 16 until I wanted to test my new project that uses react’s new context api.
If I render only my basic component using shallow and console log the debug of the component I can see its content but when I use the new context api with provider and consumer, I get <undefined />
as a render out. Enzyme does not render the component but react does.
Can someone please provide some guidance.
Thank you.
The new React Context API, introduced with React v. 16.3, allows us to pass data through our component trees, giving our components the ability to communicate and share data at different levels. In this tutorial, we'll explore how we can use React Context to avoid prop drilling.
The simple way to access the context values is by wrapping the child component in the Consumer for Class component and for the functional component we can access context with the help of useContext method of React. From there, we can access the context value as props.
The legacy context API will be removed in a future major version. Use the new context API introduced with version 16.3. The legacy API will continue working for all 16.
If you're looking for a big store where you can dynamically manage data and constantly update it, Redux is the way. If you need both, my opinion is that it's perfectly okay to do so.
Support for this and other React 16.3 features are going to be included in the next enzyme release which is going to happen in midst summer, this year (as said here).
For now, here's a workaround:
const outer = shallow(<SimpleComp />);
const Children = outer.props().children({ /* context */ });
const wrapper = shallow(Children);
To use mount() with new Context API use this enzyme patch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With