title: How to mock ResizeObserver to work in unit tests using react testing library
body: <p>If anyone can help, I have a custom hook that uses ResizeObserver to change the width of a component. My problem is that when I go to run my units test it breaks all my tests and looking at the snapshot it is not rendering all the elements in the dom. It was working before until I implemented the ResizeObserver. Does anyone know if there is a way I jest.mock the ResizeObserver to not undefined. Or other suggestions.</p>
  <pre><code>import * as React from 'react';
  import ResizeObserver from 'resize-observer-polyfill';
  
  const useResizeObserver = (ref: { current: any }) =&gt; {
      const [dimensions, setDimensions] = React.useState&lt;DOMRectReadOnly&gt;();
      React.useEffect(() =&gt; {
          const observeTarget = ref.current;
          const resizeObserver = new ResizeObserver((entries) =&gt; {
              entries.forEach((entry) =&gt; {
                  setDimensions(entry.contentRect);
              });
          });
          resizeObserver.observe(observeTarget);
          return () =&gt; {
              resizeObserver.unobserve(observeTarget);
          };
      }, [ref]);
      return dimensions;
  };
  
  export default useResizeObserver;
  
  
  
  import { render, screen, waitFor } from '@testing-library/react';
  import userEvent from '@testing-library/user-event';
  import React from 'react';
  
  import mockFetchProfileActivity from '../../../services/mocks/fetch-profile-activity';
  import BarChart from './BarChart';
  
  const component = &lt;BarChart userActivity={mockFetchProfileActivity} /&gt;;
  
  describe('Render barElement Chart component', () =&gt; {
      const observers: any[] = [];
      let resizeHandler: (observers: any[]) =&gt; void;
      (window as any).ResizeObserver = (e: any) =&gt; {
          resizeHandler = e;
  
          return {
              observe(element: any) {
                  observers.push(element);
              },
              unobserve(element: any) {
                  const i = observers.indexOf(element);
                  if (i !== -1) {
                      observers.splice(i, 1);
                  }
              }
          };
      };
  
      it('Matches the snapshot', () =&gt; {
          // resizeHandler(observers);
          const container = render(component);
          expect(container).toMatchSnapshot();
      });
  
      it('when clicking on a chart barElement drilldown &quot;challenges&quot; are shown', async () =&gt; {
          // arrange
          const componentRender = render(component);
          waitFor(() =&gt; resizeHandler(observers));
  
          // act
          const barElement = componentRender.container.querySelector('svg rect');
  
          if (barElement) userEvent.click(barElement);
  
          // assert
          expect(screen.getByText('Challenge 1')).toBeInTheDocument();
      });
  });
  </code></pre>