我正在编写一个 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);
});
最佳答案
由于 jsdom
实际上并不呈现文档,因此通常不会实现大小属性并返回一个固定的 0。
对于naturalHeight
,它是seems就像它实际上回到了 height
属性。
因此我看到两个选项:
<强>1。手动分配高度
:
wrapper.find('img').node.height = 120;
<强>2。扩展HTMLImageElement
的原型(prototype):
Object.defineProperty(HTMLImageElement.prototype, 'naturalHeight', { get: () => 120 });
关于javascript - 在没有 DOM 的情况下测试图像的 'naturalHeight',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46507306/