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.
import * as React from 'react';
import ResizeObserver from 'resize-observer-polyfill';
const useResizeObserver = (ref: { current: any }) => {
const [dimensions, setDimensions] = React.useState<DOMRectReadOnly>();
React.useEffect(() => {
const observeTarget = ref.current;
const resizeObserver = new ResizeObserver((entries) => {
entries.forEach((entry) => {
setDimensions(entry.contentRect);
});
});
resizeObserver.observe(observeTarget);
return () => {
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 = <BarChart userActivity={mockFetchProfileActivity} />;
describe('Render barElement Chart component', () => {
const observers: any[] = [];
let resizeHandler: (observers: any[]) => void;
(window as any).ResizeObserver = (e: any) => {
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', () => {
// resizeHandler(observers);
const container = render(component);
expect(container).toMatchSnapshot();
});
it('when clicking on a chart barElement drilldown "challenges" are shown', async () => {
// arrange
const componentRender = render(component);
waitFor(() => resizeHandler(observers));
// act
const barElement = componentRender.container.querySelector('svg rect');
if (barElement) userEvent.click(barElement);
// assert
expect(screen.getByText('Challenge 1')).toBeInTheDocument();
});
});
Property 'ResizeObserver' does not exist on type 'Global & typeof globalThis'
– Chicanery