12

I am using react-testing-library and jest. In componentdidupdate trying to get 'this.testRef.current.offsetHeight', getting offsetHeight as 0 even after content is loaded. I want DOM's exact offsetHeight because of having some conditions based on it.

Is there any possible solution to resolve in react-testing-library and jest.

I am using dangerouslySetInnerHTML to binding html content for testRef's element.

Lin Du
  • 88,126
  • 95
  • 281
  • 483
Divya
  • 357
  • 1
  • 3
  • 13
  • 3
    Jest doesn't render the DOM so the element doesn't really exist (so it can't have a height.) You have to mock such values. – JJJ Apr 03 '19 at 06:03
  • @JJJ As am new to this, I tried to mock data using jest.spyOn(). I don't know how to mock createRef get function for that component? import MyCompont from 'components/mycomponent'; I need MyCompont's ref's offsetHeight value. Can you provide me example? I tried using this(https://stackoverflow.com/questions/53721999/react-jest-enzyme-how-to-mock-ref-properties). I did't use enzyme here. – Divya Apr 03 '19 at 09:36

1 Answers1

19

You can do something like this :

  const originalOffsetHeight = Object.getOwnPropertyDescriptor(
    HTMLElement.prototype,
    'offsetHeight'
  );
  const originalOffsetWidth = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetWidth');
  beforeAll(() => {
    Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {
      configurable: true,
      value: 200,
    });
    Object.defineProperty(HTMLElement.prototype, 'offsetWidth', { 
      configurable: true, value: 200 
    });
  });

  afterAll(() => {
    Object.defineProperty(HTMLElement.prototype, 'offsetHeight', originalOffsetHeight);
    Object.defineProperty(HTMLElement.prototype, 'offsetWidth', originalOffsetWidth);
  });
Satyam Neekhra
  • 191
  • 1
  • 3
  • This sets the `offsetWidth` and `offsetHeight` values of all the elements in the test to. Is there a way this method can target a specific element? – Avi Jul 20 '23 at 09:34