Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    React Testing: Conditional className with Shallow Rendering

    Trevor MillerTrevor Miller

    Often our components have output that shows differently depending on the props it is given; in this lesson, we go over how to compare the className prop element tree output based on conditional input.

    reactReact
    0.14 - 15
    Code

    Code

    Become a Member to view code

    You must be a 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
    Transcript

    Transcript

    00:00 Here we have an app that lets us add quotes to a list and then like and unlike those quotes. We like to test that the className gets applied correctly based on the conditions of this like counter component here. Inside of my like counter test file I've set up the imports for React and the React test library as well as my assertion library and my component itself. I've also set up the basic describe block for the test.

    00:30 Now to write our test let's first write an IT-Block and say that it should show the like count is active. Next, let's create our shallow render. Then we can render out our component, so our like counter component. It accepts a count, which is the count of likes that are currently in the component as well as the active state.

    00:53 We'll say "is active," and for this test we're going to test that the like count renders correctly when it is active. So we'll say "True" inside of "Is active." Now I'll set up my assertions, so we'll expect the actual value is going to equal the expected value. Now my actual value is going to be whether or not the rendered element contains the className that we're expecting.

    01:16 We'll check the shallow render output and then look at the className prop. We want to make sure that that includes the like counter active string. We're expecting that when the like counter component gets rendered that, depending on this prop, this "Is active" prop, that it will render the correct className.

    01:37 Because, in this situation that we passed in "True" to "Is active," we're going to say that our expected value is going to be true. Now this test is complete, but we still want to check and make sure that if "is active" is false that the class gets rendered correctly as well, so let's create a similar test.

    01:55 Here I've added a new test, and our original test is here. In the new test, you can see that the main differences are that "Is active" is false instead of true and that we expect the like counter active class string to not be inside of the className prop. That is how you can test conditional ClassNames.

    Discuss

    Discuss