我遇到了一个问题,clientHeight是undefined,而不是DOM元素的实际高度。此代码按照浏览器中的预期工作。
组件
class MyWidget extends React.Component {
constructor() {
super();
this.state = { contentHeight: 0 };
}
componentWillReceiveProps(nextProps) {
this.setState(() => ({
contentHeight: nextProps.open ? this.content.firstChild.clientHeight : 0
}));
}
render() {
const { controlId, open, trigger, children } = this.props;
return (
<div>
<button tabIndex="0" aria-controls={controlId}>
{ cloneElement(trigger, { open }) }
</button>
<div
id={controlId}
ref={(element) => {
this.content = element;
}}
aria-hidden={open}
style={{ maxHeight: this.state.contentHeight }}
>
{ cloneElement(children, { open }) }
</div>
</div>
);
}
}但是,当挂载组件和模拟道具更改时,子clientHeight div报告undefined。
单元测试
// Arrange
const wrapper = mount(
<MyWidget trigger={<span>click me</span>} open={false}>
<div style={{ height: 90, padding: 5 }}>Lorum Ipsum</div>
</MyWidget>
);
// Act
wrapper.setProps({ open: true });
// Assert
expect(wrapper.children('div').prop('style')).to.have.property('maxHeight', 100);
// Result
AssertionError: expected { maxHeight: undefined } to have a property 'maxHeight' of 100, but got undefined我并不完全相信酶是导致这一现象的原因,因为它似乎与潜在的react-dom/test-tools和/或jsdom有关。我在酶讨论上添加了一个注释,因为我希望在进一步调试这方面的帮助。
发布于 2018-04-12 17:11:45
jsdom只提供一个DOM --它不会可视化地呈现您的内容。因此,元素没有宽度或高度。
因为您已经使用maxHeight设置了firstChild.clientHeight,所以值最终为undefined,因为定义clientHeight需要可视化呈现。
如果您需要在测试代码中验证高度或宽度,您可能需要尝试使用PhantomJS或无头Chrome --即能够可视化呈现内容的无头浏览器。
https://stackoverflow.com/questions/48112685
复制相似问题