Testing with Children DOM Elements

Learn how to test Components using their children DOM elements with various Enzyme methods.

Testing nested markup

So far, we’ve used React to encapsulate the functionality of a single DOM element (<button>) in a component (CarouselButton). But React components are capable of doing more than that. Next, we’ll build the CarouselSlide component, which will be responsible for rendering several distinct DOM elements:

  • An <img> to display the actual image
  • A <figcaption> to associate caption text with the image
  • Text, some of which will be wrapped in <strong> for emphasis
  • A <figure> to wrap it all up

We’ll take a TDD approach to building this tree while ensuring that the props we provide to CarouselSlide are routed correctly.

  • Start by creating a “stub” of the component. It’s a minimal implementation you can add functionality to later:

    // src/CarouselSlide.js
    import React from 'react';
    
    const CarouselSlide = () => <figure />;
    
    export default CarouselSlide;
    
  • Now for the tests. A good way to start is to check that the right type of DOM element is rendered:

    // src/tests/CarouselSlide.test.js
    import React from 'react';
    import { shallow } from 'enzyme';
    import CarouselSlide from 
    '../CarouselSlide';
    
    describe('CarouselSlide', () => {
      it('renders a <figure>', () => {
        const wrapper = shallow(<CarouselSlide />);
        expect(wrapper.type()).toBe('figure');
      });
    });
    

This test should be green. So let’s add some requirements. We want the <figure> to contain two children: an <img> and a <figcaption>, in that order. Enzyme’s shallow wrapper API has a childAt(index) method that should be helpful here:

Finding elements at specific positions using childAt(index)

Following is the code to find elements at specific positions using childAt(index):

Get hands-on with 1200+ tech skills courses.