Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    React Testing: Utility modules

    0.14 - 15

    When writing tests for our React code, it is helpful to pull out any functionality that doesn't have to do with our UI components into separate modules, so that they can be tested separately. In this lesson, we will take a look at a React component and how we can pull out some of its generic utility logic into a separate module. We will then write some tests for that module.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    Here we have an app that lets you add your favorite quotes to a collection. We're going to be testing that when these quotes get added that they have a unique ID. As you can see here from this quote component, there's an ID property that has a string, a unique number, and then the first part of the description of the quote.

    Currently the function that creates this unique ID is a method inside of the "add quote" React component. Because this function doesn't have anything to do with our React component, we can pull it out into its own module that we can test separately, so I'm going to cut this function from this component and create its own module file. I'll paste it in there.

    Then I'm going to export it as the default function from this file. Now, if we go back to our React component that was using it, we can go down to where it's creating the ID. Instead of using the this.createID I'm going to import our new module. Now we're ready to write a test for this module separate from the React component.

    To write our test I'm going to import Expect from Expect. Then I'm going to also import the module that we just create called createID. For our describe block we'll say createID. Then for our test we'll say that it should convert a description into a unique ID. I'm going to expect the actual value to equal the expected value.

    Now our actual value is going to be the result of using the createID module with a unique number and a description. We will expect that result to be the unique number concatenated with the first two words of the description all together in kebab-case without spaces. Now if we run our test we can see that it's passing.

    As we've done in this lesson, I've found it really helpful to take functions that are unrelated to your React components and to pull them out into their own modules like this. That way it's easier to test them and to reuse them.