15
votes

I am completely new to react-testing-library. I just started reading all the various "Getting Started" documentation and blog posts I could find after I had no success testing a component with Enzyme. Most of the examples I could find are pretty simple, like those in the "Introducing the react-testing-library" blog post. I would like to see examples of how to test a component that itself is composed of other components, since Component composition is one of the greatest things about React (in this SO post I will call an example of such ComposedComponent for lack of a better name).

When I wrote tests for a ComposedComponented in Enzyme, I could just assert that the correct props were passed to some ChildComponent and trust that ChildComponent had its own tests and I would not have to be concerned with what ChildComponent actually rendered to the DOM within my tests for ComposedComponent. But with react-testing-library, I am concerned that since "rather than dealing with instances of rendered react components, your tests will work with actual DOM nodes", I will also have to test the behavior of ChildComponent by making assertions about the DOM nodes it renders in response to its relationship to ComposedComponent. That would mean that the higher up I go in the Component hierarchy in a React application, the longer and more exhaustive my tests would become. The gist of my question is this: How can I test the behavior of a component that has other components as children without also testing the behavior of those child components?

I truly hope that I am just suffering from a failure of imagination and somebody can help me figure out how to properly use this library that has gained such a following as a replacement for Enzyme.

1

1 Answers

9
votes

What I do when testing components that happen to render other (already tested) components is mock them. For example, I have a component that displays some text, a button, and a modal. The modal itself is already tested so I don't want to test it again.

import React from 'react';
import { render, fireEvent } from '@testing-library/react';
import { ComponentUnderTest } from '.';

// Mock implementation of a sub component of the component being tested
jest.mock('../Modals/ModalComponent', () => {
  return {
    __esModule: true,
    // the "default export"
    default: ({ isOpen, onButtonPress }) =>
      isOpen && (
        // Add a `testid` data attribute so it is easy to target the "modal's" close button
        <button data-testid="close" onClick={onButtonPress} type="button" />
      ),
  };
});

describe('Test', () => {
  // Whatever tests you need/want
});