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

Already subscribed? Sign In

Autoplay

    Shallow Render a React Component with Enzyme

    Tyler ClarkTyler Clark

    In this lesson we will shallow render a component and pass through different config options. Shallow rendering is useful to test components as individual units. This helps ensure that tests aren’t indirectly asserting on behavior of child components. We’ll also use the debug method to show how we can easily view our component for debugging purposes.

    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 Shallow rendering is useful to constrain yourself to testing a component as a unit and to ensure that your test aren't indirectly asserting a behavior of child components.

    00:11 Let's go ahead and import shallow from Enzyme. Then let's create our first describe block with our app component. Inside this, we'll make an it block that just renders our app component.

    00:24 Next, we'll do a const wrapper = shallow app component. Perfect.

    00:30 As I mentioned, shallow rendering is easy to use when working with the component itself. It's not going to chase rendering child components. We could see what this shallow rendered component looks like by using the debug method on the wrapper.

    00:44 Now let's go ahead and check out this app component, see what it looks like. This is the create-react-app static app component. This is what we expect to see inside of our terminal when we run our test script.

    00:59 Our test will run and we'll see a console.log with the shallow rendered component here. As you can see, it's the same from what we see in our file.

    01:10 Now to test the rendering of children, we can create a quick react functional component called test that renders a div with testing. If we place this inside of our app component, we can see this new rendered log, and then it's not chasing the div testing child component here.

    01:34 We also have the ability to pass through some configurations to our shallow rendered component. Our second parameter here is going to be an object with a context property, as well as a disable life cycle methods property.

    01:49 As you probably guessed, this is how we can provider context to our rendered component if we care about that in our test. This disable life cycle methods property with the bool value is how we could tell Enzyme to ignore the component.mountlifecyclemethod. The component.update is also not called after setProps and setContext is used.

    Discuss

    Discuss