Testing the useTheme Hook

Now that we have defined the ThemeContextWrapper component, we can make use of it while testing the useTheme Hook.

Let's now test the useTheme Hook as outlined in the following steps:

  1. Create a new src/hooks/useTheme.test.js file.
  2. Import the renderHook function as well as the ThemeContextWrapper and the useTheme Hook:
import { renderHook } from '@testing-library/react-hooks'
import { ThemeContextWrapper } from './testUtils'
import useTheme from './useTheme'
  1. Next, define the test using the renderHook function and pass the wrapper as a second argument to it. Doing this will wrap the test component with the defined wrapper component, which means that we will be able to use the provided context in the Hook:
test('should use theme', () => {
const { result } = renderHook(
() => useTheme(),
{ wrapper: ThemeContextWrapper }
)
  1. Now we can check the result of our Hook, which should contain the colors defined in the ThemeContextWrapper:
    expect(result.current.primaryColor).toBe('deepskyblue')
expect(result.current.secondaryColor).toBe('coral')

As we can see, after providing the context wrapper, we can test Hooks that use context just like we tested our simple Counter Hook.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.83.150