Sitemap
Igor Pasieczny

Igor Pasieczny

Testing React Context

2 min readDec 29, 2018
Press enter or click to view image in full size

This article covers testing React components using React Context to pass and set some values between the whole application. The underlying problem is testing Context.Consumer without creating a mock logic for Context.Provider, as we don’t won’t to mix component logic with the test itself.

Imagine a modal that is triggered from different components across the whole app. Thanks to React Context we can avoid passing callbacks throughout the whole tree, but when it comes to testing, the regular approach would be to render the top component and check whether action makes the modal appear in the DOM. To test components in isolation I’d prefer to render just one component and see if the method I’m expecting is called. Another important thing to remember is to keep track of what’s passed to the consumer, to make sure that the types are correct.

Setup

For the setup we need three components: one acting as a Context.Provider to which we will pass one of the values from the current state and the setter for this value. The second will be the Context.Consumer, where we will use the context and set the value. Third one is just a simple mockup of a component using current state as a prop.

Modal context file:

Context provider file:

Testing

What we want to achieve is testing ModalButton component in separation of others components. It doesn’t really make any sense in an example, but imagine if ModalButton component would be deep down in the components tree — wouldn’t that be much simpler to just render this tiny component and test it’s behavior?

Get Igor Pasieczny’s stories in your inbox

Join Medium for free to get updates from this writer.

To achieve that, our test will require to mock context, but without introducing any logic — we will just test if the right function was called. Notice that ModalButton is wrapped in Context.Provider — thanks to that, we can keep track of what’s passed to the underlying component with PropTypes and ensure that the types are right.

The test itself will be divided into following steps:

  1. We render the component using react-testing-library (shout-out to Kent C. Dodds).
  2. We click the ‘modal button’ spying on the right context function.
  3. We assert that mocked function was called.

Test file will look as following:

We are not testing anything more complicated than just calling the function. You can obviously use toBeCalledWith() to assert on values passed to the function.

Whole repository (without any fancy UI) can be found here:

Let me know if you have any suggestions!

Cheers
Igor — member of TheBrain Software House

Photo by Charles Deluvio 🇵🇭🇨🇦 on Unsplash

--

--