Testing: React hooks, Redux and Jest
Test configuration can often be the biggest barrier when coming to write tests. I’d like to share a quick snippet that I use when testing React Hooks that rely on a Redux state.
First, install @testing-library/react-hooks
, as this is the helper library we’ll use to test hooks.
Next, in your test file:
import { combineReducers, createStore } from 'redux'const store = createStore(combineReducers({ /* Add reducers that your hook needs */}))
You can alternatively use configureStore
if you’re using Redux Toolkit, but the main thing here is to set up a store which creates the state your hooks need.
Create a basic Wrapper component:
import { Provider } from 'react-redux'const Wrapper = ({ children }) => (
<Provider store={store}>{children}</Provider>
)
Finally, to test the hook itself with a Redux state, pass in the Wrapper component as a parameter to renderHook
:
import { renderHook } from '@testing-library/react-hooks'renderHook(() => useCustomHook(), {
wrapper: Wrapper,
})
useCustomHook
will be rendered as a child of Wrapper
, thus giving it access to the store you created in Step 1.