【问题标题】:What does react test-utils expect when it refers to ReactComponent tree?react test-utils 在引用 ReactComponent 树时期望什么?
【发布时间】:2015-03-21 13:45:21
【问题描述】:

我正在尝试为通过 react 组件呈现的一些 d3 元素编写测试,我希望能够挑选出页面上的一些 svg 元素并检查它们的宽度以查看它们是否正常运行正如预期的那样。

我不完全确定 react test-utils 文档在说 ReactComponent 树时会期待什么。

array scryRenderedDOMComponentsWithClass(ReactComponent tree, string className)

我正在通过以下方式将我的组件渲染到文档中:

  var component = TestUtils.renderIntoDocument(
    <ProgressCircle percentage={75} />
  );

我可以通过以下方式成功检查 css className:

  it('should render an element with the class "progress-circle"', function() {
    var circleContainer = TestUtils.findRenderedDOMComponentWithClass(component, 'progress-circle');
    expect(circleContainer).toBeDefined();
  });

但我不明白我需要为其中一些需要 ReactComponent 树的 find / scry 方法提供什么。

http://facebook.github.io/react/docs/test-utils.html

编辑:

为了更清楚,这个组件的渲染 DOM 看起来像这样:

<div class="progress-circle">
  <svg>
    <g>
    </g>
  </svg>
</div>

...我正在寻找元素。

【问题讨论】:

    标签: reactjs jestjs


    【解决方案1】:

    据我了解,TestUtils.renderIntoDocument() 返回一个 ReactComponent 树。然后,您可以从该树中拉出单个组件来测试它们。

    例如,我通过了这个测试。

    it('demonstrates the ReactComponent tree', function() {
      var React = require('react/addons');
      var TestUtils = React.addons.TestUtils;
      var MyComponent = require('../MyComponent.jsx');
    
      var renderedTree = TestUtils.renderIntoDocument(<MyComponent />);
      var renderedMyComponent = TestUtils.findRenderedDOMComponentWithClass(renderedTree, 'my-component')
    
      expect(TestUtils.isDOMComponent(renderedMyComponent)).toBe(true);
    });
    

    因此,如果您只是渲染单个组件,它将是renderedTree 的根。但是您仍然必须在 renderedTree 中找到呈现的 MyComponent,然后才能检查针对它的断言。

    【讨论】:

    • 补充一点,renderIntoDocumentReactDOM.render 的一个非常基本的包装器。根据the docs,它返回一个指向正在渲染的根组件/元素的引用。所以我假设“树”只是指充当根的组件实例或 DOM 元素。它还说功能组件将返回null,所以要小心。目前,由于即将发生更改,不鼓励使用此返回的 ref,建议您以正常方式创建 ref。
    猜你喜欢
    • 2019-08-08
    • 1970-01-01
    • 2016-04-02
    • 2016-07-09
    • 2019-03-28
    • 2018-04-05
    • 1970-01-01
    • 2019-02-10
    • 2021-07-05
    相关资源
    最近更新 更多