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 react-responsive to return different markup based on the matching media query. The window.innerWidth defaults to 1024px but the tests don't seem to "see" that. Only markup that is not wrapped in a media query will render.
Is this issue specific to RTL? Do I need to mock useMediaQuery in the test?
Here is a simple component and test to illustrate the issue:
// 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 => {
const isMobile = useMediaQuery({ query: MOBILE_MEDIA_QUERY })
const isDesktop = useMediaQuery({ query: DESKTOP_MEDIA_QUERY })
if (isMobile) {
return <div>mobile</div>
} else if(isDesktop) {
return <div>desktop</div>
} else {
return <div>media queries did not match</div>
}
}
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 () => {
console.log(`this window.innerWidth is: ${window.innerWidth}`)
render(<Test/>)
expect(await screen.findByText('desktop')).toBeInTheDocument()
})
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 isDesktop did not render even though the viewport is set to a width of 1024. The only markup that renders is that which is not wrapped in a media query. I'm not even trying to change the viewport width right now. I'm just trying to get it to acknowledge the default viewport width and render accordingly.
