Last active
November 7, 2018 12:48
-
-
Save DawChihLiou/f23ef90442fd4ef790a46ac0ffc5ad68 to your computer and use it in GitHub Desktop.
Test React Hooks
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 { useState, useEffect } from 'react'; | |
export default function useViewport() { | |
const [viewport, setViewport] = useState(); | |
const handleResize = () => { | |
if (window.innerWidth > 1280) { | |
setViewport('extra-large'); | |
} else if (window.innerWidth > 816) { | |
setViewport('large'); | |
} else if (window.innerWidth > 664) { | |
setViewport('medium'); | |
} else { | |
setViewport('small'); | |
} | |
}; | |
useEffect(() => { | |
window.addEventListener('resize', handleResize); | |
return () => { | |
window.removeEventListener('resize', handleResize); | |
}; | |
}); | |
return viewport; | |
} |
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 { render } from 'react-testing-library'; | |
import useViewport from './useViewport'; | |
function fireResize(width) { | |
window.innerWidth = width; | |
window.dispatchEvent(new Event('resize')); | |
} | |
function EffecfulComponent() { | |
const viewport = useViewport(); | |
return <span>{viewport}</span>; | |
} | |
test('useViewport listen to window resize and set viewport size responsively', () => { | |
const { container, rerender } = render(<EffecfulComponent />); | |
const span = container.firstChild; | |
rerender(<EffecfulComponent />); | |
fireResize(400); | |
// useEffect is triggered after rendering. | |
// So we want to rerender the component to see the state change | |
rerender(<EffecfulComponent />); | |
expect(span.textContent).toBe('small'); | |
fireResize(800); | |
rerender(<EffecfulComponent />); | |
expect(span.textContent).toBe('medium'); | |
fireResize(1200); | |
rerender(<EffecfulComponent />); | |
expect(span.textContent).toBe('large'); | |
fireResize(1400); | |
rerender(<EffecfulComponent />); | |
expect(span.textContent).toBe('extra-large'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment