Test React Components that use React Hooks

Kent C. Dodds
InstructorKent C. Dodds
Share this video with your friends

Social Share Links

Send Tweet

Testing our <Counter /> React Component that uses the useState hook is actually very straightforward with react-testing-library. Let's give it a whirl!

Instructor: [00:00] Here we have a simple counter that uses the use-state hook. Let's go ahead and get this tested. I'm going to import that counter from counter, and then we'll make a test that says that counter increments the count.

[00:14] Now we're going to want to render that. Let's go ahead and we'll import render from React Testing Library. When we render it, we're going to want to use React from React to use JSX. Then we'll say counter right here.

[00:33] In our counter -- this is a pretty contrived example, but -- the first item, or the first child is the button, so we'll go ahead and just do that. We'll say const-container equals render.

[00:43] We'll say const-button equals container.firstchild. Then we can go ahead and fire a click event.

[00:50] Let's bring in fireEvent. We'll say fireEvent.click on the button, and we'll expect the button.textContent to be one. Cool, we got our test pass in there. Let's make sure that it can fail, so that our assertion actually is running. Cool.

[01:11] Let's go ahead and add another assertion here that initializes to zero, and we're all set. As you can see here, React's Testing Library allows us to write our tests that are free of implementation details. It works whether our counter is a cost component or a function component that uses React hooks.

[01:28] In review, all that we needed to do was bring in React, React Testing Library and the counter component, then we rendered and got the container for that counter. We got the first child, which was the button. Then we expected that the button's contents were zero. We fired a click event and then expected it to be one.