Test New Component State with setState in Enzyme

Tyler Clark
InstructorTyler Clark

Share this video with your friends

Send Tweet
Published 5 years ago
Updated 3 years ago

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.

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.