Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Toggling between 'print' and 'screen' media types? #27

Open
jrnail23 opened this issue Feb 14, 2025 · 0 comments
Open

Toggling between 'print' and 'screen' media types? #27

jrnail23 opened this issue Feb 14, 2025 · 0 comments

Comments

@jrnail23
Copy link

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:

  1. render the page normally (screen media)
  2. assert the expected UI components are visible
  3. switch to print media (act(() => { matchMedia.useMediaQuery('print') }))
  4. assert the expected print-only components are rendered
  5. switch back to screen media (act(() => { matchMedia.useMediaQuery('screen') }))
  6. 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?

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant