Now that we have defined the StateContextWrapper, we can use it to test the useDispatch Hook.
Let's test the useDispatch Hook with the following steps:
- Create a new src/hooks/useDispatch.test.js file.
- Import the renderHook function, the StateContextWrapper component, and the useDispatch Hook:
import { renderHook } from '@testing-library/react-hooks'
import { StateContextWrapper } from './testUtils'
import useDispatch from './useDispatch'
- Then, define the test function, passing the StateContextWrapper component to it:
test('should use dispatch', () => {
const { result } = renderHook(
() => useDispatch(),
{ wrapper: StateContextWrapper }
)
- Finally, check whether the result of the Dispatch Hook is a function (the dispatch function):
expect(typeof result.current).toBe('function')
})
As we can see, using a wrapper component always works the same way, even if we use other Hooks within the wrapper component.