React testing library cannot find any components used inside react-responsive media queries

I am using react-responsive to display some elements inside a react component. I have an integration test that takes a snapshot of the app, but the snapshot shows me an empty span where the media query component should be. It's as if the testing library doesn't know how to use react-responsive media queries because if I comment the media queries out and replace with a simple span then the snapshot will print that.

I have looked through docs online but have not found a solution that works.

Tried adding this to the top of test file:

global.window.matchMedia = jest.fn().mockReturnValue({
matches: true,
addListener: () => {},
removeListener: () => {},

});

This is an example of the component that uses react-responsive:

const AutoInfo = ({ vehicle }) => {
  return (
    <>
      <MediaQuery maxWidth={599}>
        {<span>Contents to be shown at Mobile</span>}
      </MediaQuery>
      <MediaQuery minWidth={600}>
        {<span>Contents to be shown at Desktop</span>}
      </MediaQuery>
    </>
  );
};

This is where in the app I am using the VehicleInfo component:

<Field name={name}>
  {({ field }) => (
    <VisualCheckbox
      {...field}
      checked={field.value}
      onChange={handleOnChange(field, onChange)}
      disabled={!field.value && !allowMoreVehicles}
    >
      <IconAuto label={<AutoInfo vehicle={vehicle} />} />
    </VisualCheckbox>
  )}
</Field>

This is the rendered markup from the snapshot. This works as expected in the browser, however the snapshot does not render the markup, instead it prints out an empty span where I expect to see my formatted text:

<span class="lm-Icon-label lm-Icon--label" />

Answers:

Answer

I hope this helps someone else with similar issue.

I figured out the problem. First, I needed to add this in the beforeEach() section of my tests:

window.matchMedia('(max-width: 599px)');

Then I had to mock this matchMedia() function like so:

global.window.matchMedia = jest.fn().mockReturnValue({
  matches: true,
  addListener: () => {},
  removeListener: () => {},
});

Apparently by default the testing library has no concept of how wide the browser window is, so by adding this it now renders whatever was inside my MediaQuery component that has a max-width: 599px! Although in my snapshot it actually rendered the contents of both media queries (max-width: 599px AND min-width: 600px) but at least I was able to render the contents and fix my test.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.