1

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

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,溢出:隐藏

这是updateScrollState`SlidingContainer' 的方法

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.scrollWidth两者bodyElement.offsetWidth都等于 0。我四处搜索,似乎这是一个元素仅在内存中呈现且没有真实 DOM 的问题,即使renderIntoDocument应该将元素渲染为dom。

4

1 回答 1

1

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

于 2016-05-14T05:01:46.967 回答