Please note that @testing-library/user-event version 14 has made all APIs async and the workshop material has been updated to use the latest version of that package. So you'll need to make all tests async and use await when using that package.

Transcript

Kent C. Dodds: 0:00 All right, I know what you've all been waiting for, you want to know how to test custom hooks. I don't know, maybe this will disappoint you, but testing custom hooks is something you probably shouldn't do.

0:10 Most of the time, the custom hooks that you make are going to be used by one, maybe two components. You should just test those components and then your hook is going to be tested as an implementation detail of those things.

0:22 However, if you are building a reusable hook, or you have a library of hooks, or something like that, then yeah, that's a pretty good situation for testing a custom hook, but the way that your software is going to be used is within a component. Maybe that's how you should test a custom hook.

0:40 For our exercise, we're going to take a custom hook, put it into a test component. Just make a component that resembles the way that people normally are going to use our custom hook and then test that component rather than testing our hook directly.

0:54 Don't worry. Sometimes doing that is a little bit tricky. We do have some extra credits to show you how you can test just the custom hook directly without having to make a special test component for more complicated situations. We eventually make our way into a library that you can play around with.

1:13 Our final extra credit here is a much more practical example of a custom hook. I think you'll enjoy that one. The custom hook that we're going to be testing here in [inaudible] JS is a useCounter hook. That might be familiar.

1:27 If you jump into that, it's a custom hook that basically has state for a counter, an increment and a decrement function, then it just exports that. If you go to the deployed version of this, then that should look pretty familiar. We've just got a component that is using that thing.

1:45 In our test, your job is to create a simple function component that uses this, and then test that function component.

1:52 Have a good time with this. Make sure to get through some of that extra credit. We'll see you on the other side of the exercise.