/react-hooks-testing-library

🐏 Simple and complete React hooks testing utilities that encourage good testing practices.

Primary LanguageJavaScriptMIT LicenseMIT

react-hooks-testing-library

ram

Simple and complete React hooks testing utilities that encourage good testing practices.


Build Status codecov version downloads MIT License

All Contributors PRs Welcome Code of Conduct

Watch on GitHub Star on GitHub Tweet

The problem

You're writing an awesome custom hook and you want to test it, but as soon as you call it you see the following error:

Invariant Violation: Hooks can only be called inside the body of a function component.

You don't really want to write a component solely for testing this hook and have to work out how you were going to trigger all the various ways the hook can be updated, especially given the complexities of how you've wired the whole thing together.

The solution

The react-hooks-testing-library allows you to create a simple test harness for React hooks that handles running them within the body of a function component, as well as providing various useful utility functions for updating the inputs and retrieving the outputs of your amazing custom hook.

Similarly to react-testing-library, which this library draws much of it's inspiration from, it aims to provide a testing experience as close as possible to natively using your hook from within a real component.

Using this library, you do not have to concern yourself with how to construct, render or interact with the react component in order to test your hook. You can just use the hook directly and assert the results.

When to use this library

  1. You're writing a library with one or more custom hooks that are not directly tied a component
  2. You have a complex hook that is difficult to test through component interactions

When not to use this library

  1. Your hook is defined along side a component and is only used there
  2. Your hook is easy to test by just testing the components using it

Example

// useCounter.js
import { useState, useCallback } from 'react'

function useCounter() {
  const [count, setCount] = useState(0)

  const increment = useCallback(() => setCount((x) => x + 1), [])
  const decrement = useCallback(() => setCount((x) => x - 1), [])

  return { count, increment, decrement }
}

export default useCounter
// useCounter.test.js
import { renderHook, act } from 'react-hooks-testing-library'
import useCounter from './useCounter'

test('should increment counter', () => {
  const { result } = renderHook(() => useCounter())

  act(() => result.current.increment())

  expect(result.current.count).toBe(1)
})

test('should decrement counter', () => {
  const { result } = renderHook(() => useCounter())

  act(() => result.current.decrement())

  expect(result.current.count).toBe(-1)
})

Installation

npm install --save-dev react-hooks-testing-library

We are using react-test-renderer as a peerDependency, so make sure you have installed this library as well. Install the same version like you use in react.

npm install --save-dev react-test-renderer@x.y.z

Documentation

There are some work-in-progress docs here. Please leave any feedback on them in this issue. PRs to update them are very welcome.

API

renderHook(callback[, options])

Renders a test component that will call the provided callback, including any hooks it calls, every time it renders.

Note: testHook has been renamed to renderHook. testHook will continue work in the current version with a deprecation warning, but will be removed in a future version.

You should update any usages of testHook to use renderHook instead.

Arguments

  • callback (function()) - function to call each render. This function should call one or more hooks for testing.
  • options (object) - accept the following settings:
    • initialProps (object) - the initial values to pass to the callback function
    • wrapper (component) - pass a React Component as the wrapper option to have it rendered around the inner element. This is most useful for creating reusable custom render functions for common data providers

Returns

  • result (object)
    • current (any) - the return value of the callback function
    • error (Error) - the error that was thrown if the callback function threw an error during rendering
  • waitForNextUpdate (function) - returns a Promise that resolves the next time the hook renders, commonly when state is updated as the result of a asynchronous action.
  • rerender (function([newProps])) - function to rerender the test component including any hooks called in the callback function. If newProps are passed, the will replace the initialProps passed the the callback function for future renders.
  • unmount (function()) - function to unmount the test component, commonly used to trigger cleanup effects for useEffect hooks.

act(callback)

This is the same act function that is exported by react-test-renderer.

Contributors

Thanks goes to these wonderful people (emoji key):

Michael Peyper
Michael Peyper

💻 🎨 📖 🤔 🚇 📦 ⚠️ 🔧
otofu-square
otofu-square

💻
Patrick P. Henley
Patrick P. Henley

🤔 👀
Matheus Marques
Matheus Marques

💻
Dhruv Patel
Dhruv Patel

🐛 👀
Nathaniel Tucker
Nathaniel Tucker

🐛 👀
Sergei Grishchenko
Sergei Grishchenko

💻 📖 🤔
Josep M Sobrepere
Josep M Sobrepere

📖
Marcel Tinner
Marcel Tinner

📖
Michael Peyper
Michael Peyper

💻 🎨 📖 🤔 🚇 📦 ⚠️ 🔧
otofu-square
otofu-square

💻
Patrick P. Henley
Patrick P. Henley

🤔 👀
Matheus Marques
Matheus Marques

💻
Dhruv Patel
Dhruv Patel

🐛 👀
Nathaniel Tucker
Nathaniel Tucker

🐛 👀
Sergei Grishchenko
Sergei Grishchenko

💻 📖 🤔
Josep M Sobrepere
Josep M Sobrepere

📖
Marcel Tinner
Marcel Tinner

📖
Daniel K.
Daniel K.

🐛 💻

This project follows the all-contributors specification. Contributions of any kind welcome!

Issues

Looking to contribute? Look for the Good First Issue label.

🐛 Bugs

Please file an issue for bugs, missing documentation, or unexpected behavior.

See Bugs

💡 Feature Requests

Please file an issue to suggest new features. Vote on feature requests by adding a 👍. This helps maintainers prioritize what to work on.

See Feature Requests

❓ Questions

For questions related to using the library, you can raise issue here, or visit a support community:

LICENSE

MIT