Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Test React Components that use React Hooks


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



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: 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.

    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.

    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.

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

    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.

    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.

    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.