ReactTestUtils.renderIntoDocument 带有子项的组件 - 子项似乎 "not render in DOM"

ReactTestUtils.renderIntoDocument a component with children - children seem to "not render in DOM"

我在测试中渲染了一个组件:

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 元素。它有一个设置的宽度,whitespace: nowrap, overflow: hidden

这是“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.

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