我目前正在使用Jest和Enzyme测试React TextArea
组件。该组件基本上只是本机<textarea>
元素的包装。它的行为是根据其相对于设置max-height
的当前值自动调整其高度。这是onchange事件处理程序:
handleInputChange = e => {
const { onChange } = this.props;
const field = e.target;
field.style.height = 'inherit';
field.style.height = `${field.scrollHeight}px`;
const max = parseInt(
window.getComputedStyle(field).getPropertyValue('max-height'),
10
);
field.style.overflowY = max < field.scrollHeight ? 'scroll' : 'hidden';
if (onChange) {
onChange(e);
}
};
我想为此编写一个单元测试,以便可以测试它是否更新了它的高度。我已经对如何将onchange事件模拟为输入进行了一些研究,但到目前为止,我可以通过传递“部分填充” event
对象(它仅具有value属性)来完成它这个:
const spy = jest.spyOn(wrapper.instance(), 'handleInputChange');
const controlledTextArea = findByTestAttr(wrapper, 'controlledTextArea');
controlledTextArea.simulate('change', {
target: {
value: 'This is just for test'
}
});
但是这将导致错误,因为我需要访问style
的e.target
属性。
所以,我的问题是,如何像模拟普通事件对象一样模拟onchange事件。我希望我可以做类似的事情:
controlledTextArea.simulate('change', 'This is another test text');
然后它会自动为我创建event
对象。有没有办法做到这一点?
没有简单的方法可以实现这一目标。而且jest
在引擎盖下使用jsdom
。而且它并没有实现浏览器拥有的所有API。同样,当您在稀释中测试组件时jsdom
将无法访问所有原始CSS,因此将不返回任何内容。
总结以上所有内容,您必须同时模拟getComputedStyle
和target.style
。可能类似:
window.getComputedStyle