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

pet*_*ess 15 reactjs react-testing-library

我对反应测试库完全陌生。在使用 Enzyme 测试组件没有成功之后,我才开始阅读我能找到的所有各种“入门”文档和博客文章。我能找到的大多数示例都非常简单,例如“Introducing the react-testing-library”博客文章中的示例。我想看看如何测试一个本身由其他组件组成的组件的示例,因为组件组合是关于 React 的最伟大的事情之一(在这篇 SO 文章中,ComposedComponent由于缺乏更好的名称,我将称之为此类示例) .

当我为ComposedComponentedEnzyme中的 a 编写测试时,我可以断言正确的 props 被传递给了一些ChildComponent并且信任ChildComponent有自己的测试,我不必关心ChildComponent在我的测试中实际呈现给 DOM 的内容ComposedComponent。但是对于 react-testing-library,我担心由于“您的测试将使用实际的 DOM 节点而不是处理呈现的 React 组件的实例”,因此我还必须ChildComponent通过对 DOM 节点进行断言来测试 的行为它呈现以响应其与 的关系ComposedComponent。这意味着我在 React 应用程序的组件层次结构中越往上走,我的测试就会变得越长、越详尽。我的问题的要点是:如何在不测试这些子组件的行为的情况下测试具有其他组件作为子组件的组件的行为?

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

Dre*_*ese 9

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

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
});
Run Code Online (Sandbox Code Playgroud)