name | route |
---|---|
Introduction |
/ |
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 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.
This library 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.
- You're writing a library with one or more custom hooks that are not directly tied a component
- You have a complex hook that is difficult to test through component interactions
- Your hook is defined alongside a component and is only used there
- Your hook is easy to test by just testing the components using it
This module is distributed via npm which is bundled with
node and should be installed as one of your project's devDependencies
:
npm install --save-dev @testing-library/react-hooks
react-hooks-testing-library
does not come bundled with a version of
react
or
react-test-renderer
to allow you to install
the specific version you want to test against. Generally, the installed versions for react
and
react-test-renderer
should have matching versions:
npm install react@^16.9.0
npm install --save-dev react-test-renderer@^16.9.0
NOTE: The minimum supported version of
react
andreact-test-renderer
is^16.9.0
.
In order to run tests, you will probably want to be using a test framework. If you have not already got one, we recommend using Jest, but this library should work without issues with any of the alternatives.