This Lesson is for Members

Subscribe today and get access to all lessons! Plus direct HD download for offline use, enhances transcripts, member comment forums, and iTunes "podcast" RSS feed. Level up your skills now!

Unlock This Lesson

Already subscribed? Sign In

Autoplay

    Test New Component State with setState in Enzyme

    Tyler ClarkTyler Clark

    Sometimes our React components render different outputs depending on their local state. In this lesson we will use Enzyme’s setState method to test that our component’s rendered output is as expected.

    reactReact
    ^16.0.0
    jestJest
    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

    Instructor: 00:00 Sometimes, our React components use local state to conditionally update our component attributes. If we wanted to simulate and test different component contexts, we can manually update the rendered component inside of our testing environment.

    00:15 For our new test, we'll say it updates class name with new state. Inside of this block, we'll do const wrapper equals shallow app component. We'll expect that we find the blue class with a length on one and our red class zero. Until we update our state, we'll put main color to red. Now, we'll expect that our blue is zero and red is one.

    00:41 Now, inside of our app file, let's add our main color property, initially to be blue. Our H3 class name is this.state.mainColor. We'll say, "Everyone is welcome." Close H3 and save it. Perfect.

    00:55 Now, the only failing tests we have are snapshots. If we update these, we're going to see that our test now pass. Now, as you can imagine, when we use this setState method on our wrapper, it will invoke setState on the root component and cause it re-render.

    01:12 This is useful for testing our components in different states.

    Discuss

    Discuss