Reputation: 289
Can anyone help please: TypeError: Cannot read property 'getBoundingClientRect' of null.
handleInformationIcon = (setIndex, index) => {
this.setState({ TooltipCheck: !this.state.TooltipCheck, activeTooltip: setIndex });
const toolTipElement = document.getElementById(`tooltip_${index}`).getBoundingClientRect().top;
const pageBottomHeight = window.innerHeight - toolTipElement;
if ((pageBottomHeight < 200) && !this.state.TooltipCheck) {
window.scrollBy({
top: 200,
behavior: 'smooth',
});
} else {
window.addEventListener('scroll', this.handleScroll);
}
}
renderTooltip = (message, index) => (
<div
className="tier-tooltip"
id={`tooltip_${index}`}
>
<button
role="link"
type="button"
tabIndex="0"
aria-expanded={this.state.isTooltipCollapse}
aria-label={this.props.resources.infoIcon}
onClick={() => this.handleInformationIcon(`${index}__tier-tooltip`, index)}
className={`icon icon-information tooltip${index}`}
/>
{this.state.activeTooltip === `${index}__tier-tooltip` && (
<div
className={sn('tier-tooltip-text', this.state.TooltipCheck ? 'isOpen' : '')}
tabIndex={0}
>
<EnhancedRichText
className="tooltip__body"
htmlText={message}
/>
<FocusoutButton
role="link"
onClick={this.handleInformationIconHide}
className="link modal__close"
aria-label={this.props.resources.infoPopoverClose}
>
<span className="icon icon-close" />
</FocusoutButton>
</div>
)}
{this.state.TooltipCheck && (
<div
className="tooltip__backdrop"
onClick={this.handleInformationIconHide}
/>
)}
</div>
)
render = () => {
return (
{this.renderToolTip(message,0)}
)
}
I tried using the test cases specified in this one but still they are failing for this piece of code : Jest/React mock scrollBy and .getBoundingClientRect function.
Upvotes: 0
Views: 460
Reputation: 289
I was able to resolve this. Reference : https://github.com/jsdom/jsdom/issues/1590#issuecomment-578350151
const htmlElment = document.createElement('div');
htmlElment.setAttribute('id', 'tooltip_0');
htmlElment.getBoundingClientRect = jest.fn(() => ({
x: 851.6,
y: 200.0,
width: 8.3,
height: 17,
top: 967.0,
right: 860.0,
bottom: 984.0,
left: 851.6,
}));
const elementMock = jest.fn().mockImplementation(() => htmlElment);
document.getElementById = elementMock;
Upvotes: 0