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

How to mock the screen dimensions with useMediaQuery #228

Closed dan-klasson closed 5 years ago

dan-klasson commented 5 years ago

I'm trying to mock the width and screen dimensions with Jest. I'm importing my matchMedia mock as described in the Jest documentation.

Looking at the useMediaQuery_test.js file there's this:

window.matchMedia.setConfig({
  type: 'screen',
  width: 1200,
  height: 800
})

I've tried adding that to my test but setConfig is undefined.

How do I go about to mock this?

yocontra commented 5 years ago

@dan-klasson Have you tried using the device prop? https://github.com/contra/react-responsive#forcing-a-device-with-the-device-prop

dan-klasson commented 5 years ago

@contra I'm testing a component, and the initialization is in a custom hook. Besides, I don't like writing code in a specific way to get my tests to pass. Is there no other way?

yocontra commented 5 years ago

@dan-klasson The device prop context stuff was built specifically for testing - https://github.com/contra/react-responsive#supplying-through-context

In your test suite you can mock the device using this, either at the top-level or per test if you want to test different device configurations. It does not require you to do anything in your component differently, and it isn't really any different than what you're trying to do with window.matchMedia.setConfig except it actually works.