Testing React Hooks ⚓️

Andrew Ross
2 min readFeb 12, 2019

--

I get that an anchor isn’t a hook but I really didn’t like 🎣 emoji to represent it

React hooks are great, they let you encapsulate little bits of logic that can be shared around your app or even shared as snippets. Think of it as mixins done correctly. For all the awesomeness hooks brings us it seems to be a glaring omission on how to test them.

The current practice for testing a hook is: build a dummy component, interact with said dummy component and observe the output.

Here’s an example:

Holy setup Batman…

The big issue here is adding anymore functions to your hook will require more buttons to press and getting anymore output will require more elements to output to. There is a sense on indirection that can make it a pain to test. Case in point at the time of writing the ever useful react-use library has no tests, this is not because it’s bad library it’s because it’s hard to do.

To solve that I’ve written test-react-hooks to help make testing hooks simple and direct. Here’s the same example using test-react-hooks:

As you can see here testing is simplified, give the hook or a function that sets up the hook and observe changes in the getResult function.

Note: actions that mutate the hook have to be done in the getResult callback.

Next time you right a hook give test-react-hooks a try, if you like it give it a star and if you run into an problem raise an issue.

--

--