Ryan Johnson
2 min readApr 16, 2018

Want to learn React? Check out my new course React for Beginners: Build and app, and learn the fundamentals.

Unit testing components using React’s new Context API

With the latest release of React the Context API has finally become a first class citizen. I have just started working with it, and so far it’s been a breeze to work with, but with one small caveat— unit tests.

Beyond an official PR in enyzme to add support for the new Context API, which at the time of this writing is still in development, I haven’t been able to find many good examples of unit testing components using context. In the meantime I’ve found the following solution worked pretty well for my scenarios.

NOTE: I’m using jest and enzyme, but I’m sure the mocking technique being used can be applied to other testing solutions. For full working example see react-localize-redux v3 branch

In this example I’m creating a new context namedLocalizeContext that will be responsible for passing localization info to any components that wish to consume it.

Now let’s create a simple LanguageSelector component that consumes the LocalizeContext. By adding LocalizeContext.Consumer to our component we are able to retrieve languages and activeLanguage from LocalizeContext.Provider.

Now we have a component that renders a link for each supported language, and adds styling for the active language link. I want to add unit tests to the LanguageSelector component, but before doing that I need a way to handle the LocalizeContext.Consumer component in our tests.

For this we’re going to leverage jest’s awesome mocking capabilities — more specifically the jest.doMock method. With this we can create a utility method that is passed the required context, and returns a version of LanguageSelector with a mocked consumer.

That’s it! Now when we run each test we can pass in mock context data to drive the test. This was a very simple example, but you can also view a full working example at react-localize-redux v3 branch.

For more React, Redux, and JavaScript reading follow me on Medium or Twitter.

Ryan Johnson

fullstack web developer • JavaScript • React.js • AngularJS • Node.js