6

I have a javascript function which checks if an html

element, el, is a certain size by checking:

function isOverflow(element: string): boolean {
    const el = document.getElementById(element);
    return el.scrollHeight > el.clientHeight
}

I want to test my function. How can I set or mock the scrollHeight and clientHeight?

it('test', () => {
   const el = document.createElement("p")
   el.setAttribute("id", "overflow")

   //How to mock these? This doesn't work "Cannot assign to 'scrollHeight' because it is a read-only property"
   el.clientHeight = 2;
   el.scrollHeight = 1;

   expect(component.isOverflow("overflow")).toBe(true);
  })
yalpsid eman
  • 3,064
  • 6
  • 45
  • 71

1 Answers1

11

Figured it out:

Object.defineProperty(HTMLElement.prototype, 'scrollHeight', { configurable: true, value: 500 })
Object.defineProperty(HTMLElement.prototype, 'clientHeight', { configurable: true, value: 10 })
yalpsid eman
  • 3,064
  • 6
  • 45
  • 71
  • 2
    This also works very well for specific elements like: `const target = document.createElement('div');` and then `Object.defineProperty(target, 'scrollHeight', { configurable: true, value: 500 });` – nephiw Sep 14 '22 at 14:31