如何使用 react-testing-library 测试由其他组件组成的组件?

How to test a component composed of other components with react-testing-library?

我对 react-testing-library 完全陌生。我刚刚开始阅读所有各种 "Getting Started" 文档和博客 post,因为我使用 Enzyme 测试组件没有成功。我能找到的大多数示例都非常简单,例如 "Introducing the react-testing-library" blog post 中的示例。我想看看如何测试本身由 other 组件组成的组件的示例,因为组件组合是 React 最伟大的事情之一(在这个 SO post由于缺少更好的名称,我将调用此类 ComposedComponent 的示例)。

当我在 Enzyme 中为 ComposedComponented 编写测试时,我可以断言正确的 props 已传递给某些 ChildComponent 并相信 ChildComponent 有自己的测试,我在我对 ComposedComponent 的测试中,不必关心 ChildComponent 实际呈现给 DOM 的内容。但是对于 react-testing-library,我担心由于 "rather than dealing with instances of rendered react components, your tests will work with actual DOM nodes",我还必须通过断言它呈现的 DOM 节点来测试 ChildComponent 的行为以响应它与 ComposedComponent 的关系。这意味着我在 React 应用程序的组件层次结构中走得越高,我的测试就会变得越长、越详尽。我的问题的要点是:如何在不测试那些子组件的行为的情况下测试具有其他子组件的组件的行为?

我真的希望我只是缺乏想象力,有人可以帮助我弄清楚如何正确使用这个已经获得如此多追随者的库作为 Enzyme 的替代品。

测试碰巧呈现其他(已测试)组件的组件时,我所做的是模拟它们。例如,我有一个显示一些文本、一个按钮和一个模式的组件。模态本身已经过测试,所以我不想再测试了。

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
});