Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
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 Component Methods with Enzyme

    Tyler ClarkTyler Clark

    In this lesson we will write tests against a method that lives on our class component. We will access it with the enzyme's instance function and assert that the return values work with the correct arguments.



    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




    Instructor: As our component grows and becomes more functional, there are times when we may need to add helper methods to the class, methods that are called in lifecycles after user interaction or just to break down more complex functionality.

    Let's get to bottom here and add a new task for a function that we'll create. Let's say it HandleStrings function returns correctly. Inside this block, we have const wrapper equals shallow our app components. We'll say const with to return equals wrapper.instance.HandleStrings, Hello World as a parameter. Expect true return to be true.

    Now, at first glance, when we get our terminal, we'll see that is failing because HandleStrings does not exist on this component yet.

    We're able to access methods on this class because of enzyme's instant function. It returns the component that we've shadowed rendered, and give this access to its properties.

    Now, let's go to our app file and add this HandleStrings method, which takes the string, and for now, or just return true. This is enough to make all of our tests pass.

    Let's do a little more with this function and we'll do const FalseReturn=wrapper.instance.HandleStrings. We'll do an empty string this time. We'll except that FalseReturn is false.

    Now, if we save this, we can see that our test will fail. We want false but we're getting true. Instead of app.js, let's modify our HandleStrings where if the string is Hello World, we want to return true. Else, we'll return false. I want to save this and grab our terminal. This will pass all of our tests.

    Again, by using the instance method on our wrapper, we are able to grab properties from our class like the HandleStrings function. We can pass different arguments and assert that it works as intended.