Test New Component State with setState in Enzyme

Tyler Clark
InstructorTyler Clark
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 4 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.

egghead
egghead
~ 37 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today