Skip to content

Instantly share code, notes, and snippets.

@armand1m
Created June 6, 2018 00:09
Show Gist options
  • Save armand1m/574ba68c3fe9270484ce443f1fcec7de to your computer and use it in GitHub Desktop.
Save armand1m/574ba68c3fe9270484ce443f1fcec7de to your computer and use it in GitHub Desktop.
CRA Jest setup tests file with window.mediaMatch a simple mock
/**
* window.matchMedia mock
*
* it also exposes a custom global method called setMatchMediaProperties
* that accepts an object as parameter to merge with the default MatchMedia properties.
*/
(function matchMediaMock() {
const defaultMatchMedia = {
matches: false,
addListener() {},
removeListener() {}
};
if (!global.matchMedia) {
global.matchMedia = () => (defaultMatchMedia);
}
global.setMatchMediaProperties = properties => {
global.matchMedia = () => Object.assign({}, defaultMatchMedia, properties);
};
}())
@armand1m
Copy link
Author

armand1m commented Jun 6, 2018

Example usage testing a React Component with Jest:

import React from 'react';
import { mount } from 'enzyme';

import MobileVersionOfComponent from '../MobileVersionOfComponent';
import DesktopVersionOfComponent from '../DesktopVersionOfComponent';
import ResponsiveVersionOfComponent from './';

describe('<ResponsiveVersionOfComponent />', () => {
  it('should render DesktopVersionOfComponent when media query matches', () => {
    /** sets global `matches` to true */
    global.setMatchMediaProperties({ matches: true });

    /** render component */
    const wrapper = mount(<ResponsiveVersionOfComponent />);

    /** assert correct component was rendered */
    expect(wrapper.find(DesktopVersionOfComponent).exists()).toBeTruthy();
  });

  it('should render MobileVersionOfComponent when media query doesnt matches', () => {
    /** sets global `matches` to false */
    global.setMatchMediaProperties({ matches: false });
    
    /** render component */
    const wrapper = mount(<ResponsiveVersionOfComponent />);

    /** assert correct component was rendered */
    expect(wrapper.find(MobileVersionOfComponent).exists()).toBeTruthy();
  });
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment