yocontra / react-responsive

CSS media queries in react - for responsive design, and more.
https://contra.io/react-responsive
MIT License
7.04k stars 298 forks source link

Storyshots does not work with useMediaQuery #279

Closed Lory1990 closed 3 years ago

Lory1990 commented 3 years ago

Hi! I am using Storybook - Storyshots to make come tests, my components are responsive and I use some conditions like

 const isMobile = useMediaQuery({ query: `(max-width: 768px` })

in storybook the component works but when I run the storyshots test I get this error

 Cannot read property 'matches' of undefined
const isMobile = useMediaQuery({ query: `(max-width: 768px` })
                               ^

How can I solve?

I think the main problem is about the test structure

storybook.test.js

import initStoryshots from '@storybook/addon-storyshots'

initStoryshots({
  framework: 'react',
})

https://www.npmjs.com/package/@storybook/addon-storyshots https://storybook.js.org/docs/react/workflows/snapshot-testing

yocontra commented 3 years ago

@Lory1990 Do you have a longer stacktrace?

I'm not sure how storyshots works, but based on the error I would assume it isn't rendering in a real browser - you'll need to provide a fake device as if you were doing server side rendering so that it knows what to render: https://github.com/contra/react-responsive#forcing-a-device-with-the-device-prop

yocontra commented 3 years ago

I looked and if you want it to render in a real browser (that has media queries, which this library needs) you can use https://github.com/storybookjs/storybook/tree/master/addons/storyshots/storyshots-puppeteer but you'd probably be better off using the device prop anyways so you have more control over it.