How to trigger useLayoutEffect in a test? (with Jest and react-testing-library)
Asked Answered
L

0

6

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)

Liftoff answered 14/7, 2021 at 18:42 Comment(2)
Have you tried waiting for it to occur, e.g., await waitFor(() => expect(screen.getByTestId('label_container')).toHaveTextContent('LA'));? You'll probably have to mock/polyfill ResizeObserver as well.Uteutensil
any luck with this one? I'm running into the same problem and can't figure out how to trigger the useLayoutEffectWilbourn

© 2022 - 2024 — McMap. All rights reserved.