I´m working on a little component that changes one label based on the size of the screen. I´m using useLayoutEffect() to observe the screend size and change the label when it reaches some limit.
import React, { useLayoutEffect, useState } from 'react';
const minimumWidth = 768;
const MyComponent = () => {
const [label, setLabel] = useState('LABEL');
useLayoutEffect(() => {
const RO = new ResizeObserver((e) => {
if (e[0].target.clientWidth < minimumWidth) {
setLabel('LABEL');
} else {
setLabel('LA');
}
});
RO.observe(document.body);
return () => RO.disconnect();
}, []);
return (
<div data-testid="label_container">
{label}
</div>
);
};
export default MyComponent;
Now I need to make a test to trigger the resize of the screen and expects for the label to change. But I cant trigger the use layout effect. Already tried this:
import React from 'react';
import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';
describe('MyComponent', () => {
beforeEach(() => {
global.innerWidth = 500;
global.dispatchEvent(new Event('resize'));
});
it('should render correctly when screen width is less than 768', () => {
createComponent();
console.log(window.innerWidth);
expect(screen.getByTestId('label_container')).toHaveTextContent(
'LA'
);
});
});
const createComponent = () => {
return render(<MyComponent />);
};
But the layoutEffect is not triggered in the component. Is there a way to test this only with jest and react-testing-library? (I don´t want to use Enzyme, or Cypress)
await waitFor(() => expect(screen.getByTestId('label_container')).toHaveTextContent('LA'));
? You'll probably have to mock/polyfillResizeObserver
as well. – UteutensiluseLayoutEffect
– Wilbourn