Test React Components that use React Hooks

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

Social Share Links

Send Tweet
Published 5 years ago
Updated 3 years ago

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.

Darren Seet
Darren Seet
~ 5 years ago

Hey Kent,

I got a test is not defined error when running this in codesandbox. Am I missing some references, I tried playing with the dependencies and also imports. Even using @testing-library/react but I could not get it to work

~ a year ago

react-testing-library has been deprecated

Markdown supported.
Become a member to join the discussionEnroll Today