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: Reusing test boilerplate

    0.14 - 15

    Setting up a shallow renderer for each test can be redundant, especially when trying to write similar tests that have slight tweaks. In this lesson, we go over how you can reduce some of the overlapping code so that each test only contains the unique pieces of the test.



    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 two tests created with the shallow renderer, and we can see that there's a lot of duplication between the two. The only two unique pieces are that the prop type changes here from true to false, and the expected value changes from true to false here.

    There are a few different ways we could go about cleaning up these tests, but what I'm going to do is go up above the test and create a new describe block that will wrap both of them. I'll call this group "is active" since we're testing the activity of this like counter component.

    So I will indent my two tests, and then I will go down and close off my describe block. It's not necessary to wrap your test like this, but I find that it's helpful, especially when we're going to be creating a function to share functionality between tests, to group them together inside of their own describe block.

    Now I'm going to remove all of this duplicate content from the second test so that all we have is the assertion at the bottom. Next I'm going to cut this duplicate piece from the first test. We'll place that in its own factory function. So I'm going to say, "function render light counter," and inside of this we'll paste our contents that we cut from the test.

    Now let's make this function usable by both tests. What I'll do is we need to have a parameter for the "is active" state, so I'm going to pass in "is active." Then I'm going to use that argument. Now I'm going to remove line 14, because we don't need this assertion piece anymore. We'll do that inside of our test.

    Now instead of creating this actual variable, I'm going to return the inaudible here. Now I can use this function inside of my test, so I'm going to replace this actual value with "render light counter," and we'll pass in true as our "is active" prop. Now our expected value is also going to be true.

    Let's do the same thing with our second test. I'm going to change my actual value to be "render like counter," and this time we'll pass in false. When we do that, we're going to expect to get false back.

    As I mentioned, there are many different ways that you can do this. The main idea, the principle behind it, is to take pieces that are repetitive in your test and to pull them out into reusable parts.