title: How to Test Responsive React Components with React Testing Library
body: <p>I'm having issues testing React components if the rendered output relies on media queries. I'm using Jest and React Testing Library. The components use <code>react-responsive</code> to return different markup based on the matching media query. The <code>window.innerWidth</code> defaults to 1024px but the tests don't seem to &quot;see&quot; that. Only markup that is <strong>not</strong> wrapped in a media query will render.</p>
  <p>Is this issue specific to RTL? Do I need to mock useMediaQuery in the test?</p>
  <p>Here is a simple component and test to illustrate the issue:</p>
  <pre><code>// test component
  import React from 'react'
  import { useMediaQuery } from 'react-responsive'
  
  const MOBILE_MEDIA_QUERY = 'only screen and (max-width : 480px)'
  const DESKTOP_MEDIA_QUERY = 'only screen and (min-width: 1024px)'
  
  const Test = props =&gt; {
    const isMobile = useMediaQuery({ query: MOBILE_MEDIA_QUERY })
    const isDesktop = useMediaQuery({ query: DESKTOP_MEDIA_QUERY })
    
    if (isMobile) {
      return &lt;div&gt;mobile&lt;/div&gt;
    } else if(isDesktop) {
      return &lt;div&gt;desktop&lt;/div&gt;
    } else {
      return &lt;div&gt;media queries did not match&lt;/div&gt;
    }
  }
  
  export default Test 
  
  
  // test spec
  import React from 'react'
  import Test from './MediaQueryTest'
  import { render, screen } from '@testing-library/react'
  
  it('should render for desktop', async () =&gt; {
    console.log(`this window.innerWidth is: ${window.innerWidth}`)
  
    render(&lt;Test/&gt;)
  
    expect(await screen.findByText('desktop')).toBeInTheDocument()
  })
  </code></pre>
  <p>Here is a screenshot of what I get in the console when I run this test (see below). As you can see, the markup wrapped in <code>isDesktop</code> did not render even though the viewport is set to a width of 1024. The only markup that renders is that which is <em>not</em> wrapped in a media query. I'm not even trying to <em>change</em> the viewport width right now. I'm just trying to get it to acknowledge the default viewport width and render accordingly.</p>
  <p><a href="https://i.stack.imgur.com/4gTEv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4gTEv.png" alt="enter image description here" /></a></p>