jest-matchmedia-mock
jest-matchmedia-mock copied to clipboard
Toggling between 'print' and 'screen' media types?
I realize this lib hasn't been updated in quite a while, and may not be actively supported any longer, so this issue is probably intended to serve as a warning for others who might be trying to do the same thing I'm doing.
My React app listens to the change event for print media (e.g., below) to toggle between our normal, UI components and print-optimized UI components.
const printMediaQuery = window.matchMedia('print');
printMediaQuery.addEventHandler('change', myEventHandler);
My event handler does a setState(isPrintMedia), such that when print media is applied (e.g., chrome's print preview is rendered), my isPrintMedia state will be true, and when the print media is removed (back to screen media), isPrintMedia state will be false, and we go back to rendering our normal screen-targeted UI.
This all works as expected in the app, but testing it has been a problem using @testing-library/react (based on JSDOM). That's where jest-matchmedia-mock comes into play.
My tests exercise this flow:
- render the page normally (screen media)
- assert the expected UI components are visible
- switch to print media (
act(() => { matchMedia.useMediaQuery('print') })) - assert the expected print-only components are rendered
- switch back to screen media (
act(() => { matchMedia.useMediaQuery('screen') })) - assert the expected UI components are visible once again
Everything works as expected until we hit step 6. When we switch back to screen media, matchMedia.useMediaQuery('screen'), does not fire the change event for the printMediaQuery as expected.
@dyakovk, If I'm not using this correctly, can you tell me how you'd trigger the change event signaling that print media has been removed?