title: How to test matchMedia with react-testing-library/jest
body: <p>Code below that I need to test -</p>
  <pre><code>  const [item, setItem] = useState(() =&gt; {
      let initialItem = 'both';
  
      if (typeof window !== 'undefined') {
        if (window.matchMedia('(max-width: 1012px)').matches) {
          initialItem = 'signup';
        } else if (window.matchMedia('(max-width: 1460px)').matches) {
          initialItem = 'info';
        }
      }
  
      return initialItem;
    });
  
    if (typeof window !== 'undefined') {
      window.matchMedia('(max-width: 1012px)').addEventListener('change', (event) =&gt; {
        if (event.matches) {
          setItem('signup');
        }
      });
  
      window.matchMedia('(max-width: 1460px)').addEventListener('change', (event) =&gt; {
        if (event.matches) {
          setItem('info');
        }
      });
  
      window.matchMedia('(min-width: 1460px)').addEventListener('change', (event) =&gt; {
        if (event.matches) {
          setItem('both');
        }
      });
    }
  </code></pre>
  <p>I am struggling to test this. This is what I have at the moment -</p>
  <pre><code>test('should update layout on window resize', () =&gt; {
      window.matchMedia = jest.fn().mockImplementation((query) =&gt; ({
        matches: query !== '(max-width: 1011px)',
        media: '',
        onchange: null,
        addEventListener: jest.fn(),
        removeListener: jest.fn(),
      }));
  
      globalThis.innerWidth = 1500;
      renderTestComponent();
      expect(screen.getByTestId('item')).toHaveTextContent('both');
      
  
      // Resize the window to small
      globalThis.innerWidth = 1000;
      globalThis.dispatchEvent(new Event('change'));
      expect(screen.getByTestId('item')).toHaveTextContent('box');
  </code></pre>
  <p>How can I test that the correct item is shown when the screen changes sizes. Especially with using matchMedia?</p>