Testing ‘useContext’ React hook with Enzyme shallow

Alex Andrade
7shifts Back of House
2 min readMay 10, 2019

--

At the point I am writing this article, Enzyme (^3.5.0) still does not have support for shallow mock on a component which uses ‘useContext’. See open issue.

If you still want to use ‘useContext’ to avoid passing props down the component tree, and you need to assure the code quality writing tests, at this point you need to use mount wrapping the context provider over your component.

Using mount for testing ‘useContext’

What is wrong? ‘mount’, as the name says, mounts all the components tree, so you need to provide everything needed to the child components to be mounted e.g. Redux store, Route, and all the others libraries you might have. If the component tree is complex, it is a nightmare to mount it.

Using shallow for the same approach above you do not have the ‘<Hello/>’ elements as it is shallow mock. You would expect, using the command below, that you should have access to the component’s context, but using ‘.dive()’ will only return a provider with default values, instead of the actual context.

const componentWithUseContext = wrapper.find(Hello).dive();

The solution

While we cannot use Enzyme shallow for testing ‘useContext’, you could take advantage of jest spy to mock your provider. What you need to do is to create a custom hook to retrieve the context, in this case, ‘useAppContext’.

AppContext.js — Creating the context
App.js — Providing the context
Hello.js — Consuming the context

As we have a custom hook returning the context values, it is possible to mock the implementation of this method, in other words, we are injecting the context values we need for the test.

Hello.test.js — Testing the component which uses ‘useContext’

On the following sandbox you can find the full code and test runner.

--

--