【问题标题】:Testing image's 'naturalHeight' without DOM在没有 DOM 的情况下测试图像的“naturalHeight”
【发布时间】:2017-10-01 19:06:51
【问题描述】:

我正在编写一个 JS 测试来检查图像的 css 类是否被正确应用。该类是根据图像的naturalHeight 属性计算的。但是因为这是一个JS测试,没有DOM,所以naturalHeight在测试中总是为0。如何使用 Jest 和 Enzyme 正确测试/模拟它?

组件的简化版:

class Image extends React.Component {
    public render () {
    return (
      <img 
        src={this.props.src}
        ref={el => this.imageElement = el } 
        className={ this._computeStyle() }/>
    )
  }

  private _computeStyle() {
    if (this.imageElement.naturalHeight > 100){ 
      return 'big';
    }
    return 'small'
  }
}

尝试测试:

it('has class "big" if > 100 pixels', () => {
  let wrapper = mount(<Image src={largeImage} />);
  expect(wrapper.find('img').hasClass('big')).toBe(true);
});

【问题讨论】:

    标签: javascript reactjs enzyme jestjs


    【解决方案1】:

    由于jsdom 并未实际呈现文档,因此通常不会实现大小属性并返回固定的 0。

    对于naturalHeight,它seems 就像它实际上回退到height 属性。

    因此我看到了两种选择:

    1.手动分配height

    wrapper.find('img').node.height = 120;
    

    2。扩展HTMLImageElement的原型:

    Object.defineProperty(HTMLImageElement.prototype, 'naturalHeight', { get: () => 120 });
    

    【讨论】:

    • 谢谢!扩展原型工作。此更改是否会仅限于此测试,还是会为项目中的所有测试全局定义属性?
    • 它只会影响这个特定的测试文件
    猜你喜欢
    • 1970-01-01
    • 2023-01-09
    • 2014-12-26
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 1970-01-01
    • 2014-05-05
    • 2012-03-19
    相关资源
    最近更新 更多