用 Jest 测试 React 元素高度

Test React element height with Jest

我有一个非常简单的 React.js 组件,它用 "Read more" / "Read less" 功能装饰一长段标记。

我用 Jest 进行了一些测试, 但是,我无法断言 DOM 元素高度正在增加到原始内容的大小。

在 Jest 测试环境中,我对 getDOMNode().scrollHeight 的调用似乎 return 什么都没有。

这是包含代码和失败测试的 link 存储库:https://github.com/mguterl/react-jest-dom-question

下面是说明相同问题的代码和测试的简化版本:

简化代码

var ReadMore = React.createClass({
  getInitialState: function() {
    return {
      style: {
        height: '0px'
      }
    }
  },

  render: function() {
    return (
      <div>
        <div ref='content' className='read-more__content' style={this.state.style} dangerouslySetInnerHTML={{__html: this.props.content}} />
        <a onClick={this.expand} href='#'>Expand</a>
      </div>
    );
  },

  expand: function() {
    // This call to scrollHeight doesn't return anything when testing.
    var height = this.refs.content.getDOMNode().scrollHeight;

    this.setState({
      style: {
        height: height
      }
    });
  }
});

测试

jest.dontMock('../ReadMore');

global.React = require('react/addons');
var TestUtils = React.addons.TestUtils;
var ReadMore = require('../ReadMore');

describe('ReadMore', function() {
  var readMore;
  var content;
  var link;

  beforeEach(function() {
    readMore = TestUtils.renderIntoDocument(
      <ReadMore collapsedHeight='0px' content='<p>Hello World</p>' />
    );

    content = TestUtils.findRenderedDOMComponentWithClass(
      readMore, 'read-more__content');

    link = TestUtils.findRenderedDOMComponentWithTag(
      readMore, 'a');
  });

  it('starts off collapsed', function() {
    expect(content.getDOMNode().getAttribute('style')).toEqual('height:0px;');
  });

  it('expands the height to fit the content', function() {
    TestUtils.Simulate.click(link);
    expect(content.getDOMNode().getAttribute('style')).toEqual('height:100px;');
  });
});

开玩笑 "runs your tests with a fake DOM implementation (via jsdom) so that your tests can run on the command line" (http://facebook.github.io/jest/).

我不希望设置元素高度之类的东西,因为它不是 运行 对抗渲染引擎来计算任何 div 的高度。

我建议在任一状态或两者 ("read-more" / "read-less") 的 div 上设置标记样式 class。然后您的测试可以断言 class.

是否存在

此外 - 如果您在 "read more" 模式下根本没有设置样式属性,则应该渲染封闭的 div 以完全显示内部 div(除非您我们不只是试图展示整个内部 div)。那么是否足以测试样式属性在 "read less" 模式下具有 this.props.collapsedHeight 值,并且在 "read more" 模式下未设置?