Mocking React hooks for testing with Jest and react-testing-library
Mocking strategies for modern React components
Imagine this familiar scenario: a developer builds a life-changing todo application using React and has decided to leverage hooks to make the sharing of state logic much cleaner. Being a responsible developer with a passion for testing, they bring in jest and react-testing-library to start writing unit and integration tests for their components.
Upon implementing these component tests, a challenge arises:
How does one mock a hook’s value when its state exists outside the scope of a component?
To help solve this, we can leverage jest.mock()
Mocking our hook state with a dynamic variable
Imagine that our component relies on a useAuth() hook to share state about the user’s logged in status.
// App.tsxconst App = () => {
const { isLoggedIn } = useAuth()
const text = isLoggedIn ? 'Welcome' : 'Login'
return (
<Text>{text}</Text>
)
}
At the top of our component test, we can add a jest.mock() that includes a relative path to where our hook module is defined. We can also provide a dynamic variable called…