【问题标题】:How to test a component composed of other components with react-testing-library?如何使用 react-testing-library 测试由其他组件组成的组件?
【发布时间】:2020-04-20 05:35:11
【问题描述】:

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

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

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

【问题讨论】:

    标签: reactjs react-testing-library


    【解决方案1】:

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

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

    【讨论】:

    • 这很好,有没有可以很好地展示这个的包?
    • @NiRR 除了 jestjs?不是我曾经寻找或找到的,抱歉。
    • 我已经阅读了一些内容,我明白为什么没有。 jest.mock 被提升到文件的顶部,因此除了字符串文字或闭包之外,您不能在 jest.mock 的第一个或第二个参数中使用任何东西,在帮助程序库中几乎没有什么可做的,并且让您测试文件中包含非常困难的代码。
    • 感谢@DrewReese 的回复,忘记回来更新状态了。如果我们使用传统的函数声明(而不是箭头函数),函数名使用displayName,lint 不会报错:)
    • @BrunoMonteiro 奇怪的是,刚才在调查另一个问题时,我在参考文献中遇到了这个问题:reactjs.org/docs/…,它基本上描述了相同的命名。
    猜你喜欢
    • 2019-06-14
    • 1970-01-01
    • 2020-09-29
    • 1970-01-01
    • 2021-05-25
    • 2019-05-23
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    相关资源
    最近更新 更多