Skip to content

Instantly share code, notes, and snippets.

@thompsongl
Created March 4, 2020 23:29
Show Gist options
  • Save thompsongl/cec1e5be12078ff9e56dc78296b88e27 to your computer and use it in GitHub Desktop.
Save thompsongl/cec1e5be12078ff9e56dc78296b88e27 to your computer and use it in GitHub Desktop.
Jest testing a responsive component
import React from 'react';
import { mount } from 'enzyme';
import { act } from 'react-dom/test-utils';
import { Responsive } from './responsive';
const resizeWindow = (x: number, y: number) => {
// @ts-ignore
window.innerWidth = x;
// @ts-ignore
window.innerHeight = y;
act(() => {
window.dispatchEvent(new Event('resize'));
});
};
describe('Responsive', () => {
it('should display the window size', () => {
const component = mount(<Responsive />);
expect(component.html()).toEqual('<div>1024 x 768</div>');
resizeWindow(500, 300);
expect(component.html()).toEqual('<div>500 x 300</div>');
resizeWindow(2880, 1800);
expect(component.html()).toEqual('<div>2880 x 1800</div>');
});
});
import React, { useEffect, useState } from 'react';
export const Responsive = () => {
const [state, setState] = useState({ width: 0, height: 0 });
useEffect(() => {
updateDimensions();
window.addEventListener('resize', updateDimensions);
return () => window.removeEventListener('resize', updateDimensions);
}, []);
const updateDimensions = () => {
setState({ width: window.innerWidth, height: window.innerHeight });
};
return (
<div>
{state.width} x {state.height}
</div>
);
};
@thompsongl
Copy link
Author

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