question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[docs] Trying to mock MUI's useMediaQuery hook behaviour in Enzyme test

See original GitHub issue

Duplicates

  • I have searched the existing issues

Related page

https://mui.com/material-ui/react-use-media-query/#testing

Kind of issue

Unclear explanations

Issue description

I’m following MUI’s documentation on how to test useMediaQuery, but I am confused as to whether or not the way I am using useMediaQuery in my component, which is using MUI’s breakpoint helpers, is compatible with the testing instructions in MUI’s docs.

Context 🔦

Here’s the code in my component:

import { useTheme } from '@mui/material/styles';
import useMediaQuery from '@material-ui/core/useMediaQuery';

  const List = () => {
      const theme = useTheme();
      const isDownLargeBreakpoint = 
      useMediaQuery(theme.breakpoints.down('lg'));

      ...
      
      {isDownLargeBreakpoint && (
          <ul className="list">
            // list items
          </ul>
      )}

  }

The useMediaQuery hook works as expected when I run my app locally, it correctly toggles between true and false when I resize the screen below/above MUI’s theme lg breakpoint.

When I try to run my test with the recommended method of setup, despite the window.innerWidth falling below what would satisfy useMediaQuery to return a value of true I always get false in my test. Perhaps it’s because I’m not rerendering my component from within my test? Or do I have to do something more in my it clause to trigger what is needing to happen?

Here’s the block of code using css-mediaquery recommended by MUI:

import mediaQuery from 'css-mediaquery';

function createMatchMedia(width) {
  return (query) => ({
    matches: mediaQuery.match(query, {
      width,
    }),
    addListener: () => {},
    removeListener: () => {},
  });
}

describe('MyTests', () => {
  beforeAll(() => {
    window.matchMedia = createMatchMedia(window.innerWidth);
  });
});

Here’s how I’ve organized my test file:

import React from 'react';
import { shallow } from 'enzyme';
import mediaQuery from 'css-mediaquery';

import SessionStore from 'app/stores/SessionStore';

import CustomFields from '../CustomFields';
import CustomFieldButton from '../CustomFieldButton';

import PrepareFieldsList from '../PrepareFieldsList';

describe('PrepareFieldsList Component', () => {
  let wrapper;

  function createMatchMedia(width) {
    return (query) => ({
      matches: mediaQuery.match(query, {
        width,
      }),
      addListener: () => {},
      removeListener: () => {},
    });
  }

  beforeAll(() => {
    window.matchMedia = createMatchMedia(window.innerWidth);
  });

  const defaultProps = {
    customFields: [
      {
        data: null,
        id: 'fieldId',
        name: '',
        required: false,
        value: 'test',
      },
    ],
  };

  beforeEach(() => {
    jest.spyOn(SessionStore, 'getSession').mockReturnValue({
      hasFeature: () => true,
    });
    wrapper = shallow(<PrepareFieldsList {...defaultProps} />);
  });

  ...

  it('should render CustomFieldButton and CustomFields when hasFeature is true', () => {
    expect(wrapper.find(CustomFieldButton)).toHaveLength(1);
    expect(wrapper.find(CustomFields)).toHaveLength(1);
  });
});

Issue Analytics

  • State:closed
  • Created 9 months ago
  • Reactions:2
  • Comments:12 (5 by maintainers)

github_iconTop GitHub Comments

2reactions
mnajdovacommented, Dec 21, 2022

Re-opening so that we track the issue in order to improve the documentation.

1reaction
oliviertassinaricommented, Dec 23, 2022

I’m closing, this is beyond the scope of what we can support as a GitHub issue. Stack Overflow sounds the right place for this. The docs mentions how a polyfill can be created, the actual implementation is then up to the developers to pull off, and depend on the testing environment they use. I would recommend providing a reproduction.

If you find the root problem, sharing the solution would be great to help future people facing the same problem.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Trying to mock MUI's useMediaQuery hook behaviour in ...
Here's how I've organized my test file: import React from 'react'; import { shallow } from 'enzyme' ...
Read more >
[docs] useMediaQuery + test env (matchMedia) #16073 - GitHub
When I inject withMobileDialog into a React component, I cannot access members of the component. I've tried dive, Material UI shallow, ...
Read more >
Guide of Testing React Components with Hooks & Mocks
A step-by-step guide to using hooks and mocks to test React ... Enzyme is a JavaScript Testing utility for React that is based...
Read more >
Media queries in React for responsive design - Material UI - MUI
This is a CSS media query hook for React. It listens for matches to a CSS media query. It allows the rendering of...
Read more >
react-responsive - npm
The best supported, easiest to use react media query module. Install. $ npm install react-responsive --save. Example Usage. With Hooks.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found