DEV Community

React Hooks: Test custom hooks with Enzyme

Dinesh Pandiyan on March 23, 2019

TL;DR - Wrap your custom hook in a component and shallow render it to test implementation details. What you will learn React test stra...
Collapse
 
robertcoopercode profile image
Robert Cooper

Thanks for the post 👍🏼

I had a heck of a time getting enzyme to work with functional react components that use hooks this week. I've instead ended up adopting react-testing-library and no longer test for implementation details (you can't really test for implementation details with react-testing-library as its API doesn't allow for it). I also read Kent C Dodds post regarding his thoughts on testing implementation details, and it convinced me to use his library.

Collapse
 
pretaporter profile image
Maksim

Try github.com/mpeyper/react-hooks-tes.... I think it's little bit easier.

Collapse
 
mpeyper profile image
Michael Peyper

Thank you so much!

Collapse
 
victor95pc profile image
Victor Palomo de Castro

Another one is my library github.com/victor95pc/jest-react-h...

Collapse
 
pgangwani profile image
pgangwani

Good Work Dinesh !! Really helpful.

I have been working on hooks testing in enzyme and opened a PR some time back here --}github.com/airbnb/enzyme/pull/2041

Would you like to contribute or help?

Collapse
 
flexdinesh profile image
Dinesh Pandiyan

Thanks Pawan. I'll try to take a look when I find time.

Collapse
 
stereobooster profile image
stereobooster

use useMemo or useCallback for onChange function inside your hook

Collapse
 
flexdinesh profile image
Dinesh Pandiyan

I understand why we would need to use useMemo or useCallback but to keep the example simple, it's a good idea to avoid them.

Collapse
 
victor95pc profile image
Victor Palomo de Castro

If you guys wants to test react hooks having access to your internal states and dispatchers use my library, is super simple: github.com/victor95pc/jest-react-h...

Collapse
 
josuevalrob profile image
Josue Valenica

what about use effect??

Collapse
 
ammoradi profile image
Amir Mohammad

Amazing! Thank you <3