Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Ref's offsetheight, always returns '0' for jest test case even after the content is loaded

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.

like image 809
Divya Avatar asked Apr 03 '19 05:04

Divya


1 Answers

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);
  });
like image 146
Satyam Neekhra Avatar answered Nov 15 '22 03:11

Satyam Neekhra