Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

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

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    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.

    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 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.

    00:14 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.

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

    00:47 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.

    00:56 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.

    01:08 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.

    01:21 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.

    01:43 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.

    Discuss

    Discuss