Created
March 4, 2020 23:29
-
-
Save thompsongl/cec1e5be12078ff9e56dc78296b88e27 to your computer and use it in GitHub Desktop.
Jest testing a responsive component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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>'); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Derived from https://stackoverflow.com/a/51997030