【问题标题】:ReactTestUtils.renderIntoDocument a component with children - children seem to "not render in DOM"ReactTestUtils.renderIntoDocument 一个带有子组件的组件 - 子组件似乎“不在 DOM 中呈现”
【发布时间】:2016-03-12 08:36:23
【问题描述】:

我在我的测试中渲染一个组件,如下所示:

component = TestUtils.renderIntoDocument(
  <SlidingContainer {...props}>
    <div style={divStyle}>foo</div>
    <div style={divStyle}>foo</div>
    <div style={divStyle}>foo</div>
  </SlidingContainer>
);

$bodyElement = $(ReactDOM.findDOMNode(component.refs.body));

这是来自SlidingContainer的渲染方法

return (
  <div className={rootClassName} >
    <div className="sliding-container_arrow sliding-container_arrow--left"
         onClick={this.slide.bind(this, 'left')}>
      <div className={leftArrowClassName}></div>
    </div>
    <div className="sliding-container_body" ref="body">
      { this.props.children }
    </div>
    <div className="sliding-container_arrow sliding-container_arrow--right"
         onClick={this.slide.bind(this, 'right')}>
      <div className={rightArrowClassName}></div>
    </div>
  </div>
);

如您所见,$bodyElement 是一个包含子元素的 DOM 元素。它有一个固定的宽度,空白:nowrap,溢出:隐藏

这是 `SlidingContainer' 的 updateScrollState 方法

updateScrollState($bodyElement) {
  var bodyElement = $bodyElement[0];
  var maxScrollLength = bodyElement.scrollWidth - bodyElement.offsetWidth;
  let maxToTheRight = maxScrollLength === $bodyElement.scrollLeft()
  let maxToTheLeft = $bodyElement.scrollLeft() === 0;

  this.setState({
    maxToTheRight: maxToTheRight,
    maxToTheLeft: maxToTheLeft
  });
}

此代码在我在浏览器中测试时有效,但在运行 karma/jasmine 单元测试时,bodyElement.scrollWidthbodyElement.offsetWidth 都等于 0。我四处搜索,似乎这是一个元素存在的问题仅在内存中渲染,没有真正的 DOM,即使 renderIntoDocument 应该将元素渲染为 dom。

【问题讨论】:

    标签: html css unit-testing reactjs reactjs-testutils


    【解决方案1】:

    您需要将其挂载到 DOM。使用window.body.appendChild($bodyElement)

    【讨论】:

      猜你喜欢
      • 2020-02-25
      • 2022-11-01
      • 2019-11-25
      • 1970-01-01
      • 2018-08-16
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多