maslianok / react-resize-detector

A Cross-Browser, Event-based, Element Resize Detection for React

Home Page:http://maslianok.github.io/react-resize-detector/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Proposal for documentation

Primajin opened this issue · comments

When running tests with enzyme and jest after upgrading to v6 I am getting the error:

TypeError: window.ResizeObserver is not a constructor
at new ResizeDetector (node_modules/react-resize-detector/src/ResizeDetector.tsx:138:27)

I found a similar issue here: que-etc/resize-observer-polyfill#50

I was able to mitigate the error like so:

  const { ResizeObserver } = window;

  beforeEach(() => {
    delete window.ResizeObserver;
    window.ResizeObserver = jest.fn().mockImplementation(() => ({
      observe: jest.fn(),
      unobserve: jest.fn(),
      disconnect: jest.fn(),
    }));

    wrapper = mount(
      <MyComponent />
    );
  });

  afterEach(() => {
    window.ResizeObserver = ResizeObserver;
    jest.restoreAllMocks();
  });

  it('should do my test', () => {
    // [...]
  });

I just wanted to share this in case questions come up and you'd like to add this to some FAQ or so.

Sweet thank you

Thank you! this solution also works for @testing-library/react with jest.

const { ResizeObserver } = window;

beforeEach(() => {
  //@ts-ignore
  delete window.ResizeObserver;
  window.ResizeObserver = jest.fn().mockImplementation(() => ({
    observe: jest.fn(),
    unobserve: jest.fn(),
    disconnect: jest.fn(),
  }));
});

afterEach(() => {
  window.ResizeObserver = ResizeObserver;
  jest.restoreAllMocks();
});

describe('<Dropdown />', () => {
  it('should be able to mount the component', () => {
    const { container } = render(
      <Dropdown {...props} value={props.options[0].value} />
    );