Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React’s new context api with enzyme

Tags:

reactjs

enzyme

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.

like image 689
SamTheGoodOne Avatar asked Jun 07 '18 09:06

SamTheGoodOne


People also ask

What is React's context API?

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.

Can I use context API in functional component?

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.

Is context API deprecated?

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.

Can I use both context API and Redux?

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.


1 Answers

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.

like image 76
iamarkadyt Avatar answered Oct 19 '22 15:10

iamarkadyt