Last active
October 17, 2021 22:13
-
-
Save stipsan/c15af304c2cf9a0250d59092733bb43d to your computer and use it in GitHub Desktop.
Testing with Jest: Tip #14
This file contains hidden or 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 renderer from 'react-test-renderer' | |
import Viewport from '../Viewport' | |
it('should render correctly', () => { | |
const target = { | |
innerHeight: 600, | |
innerWidth: 800, | |
addEventListener: jest.fn(), | |
removeEventListener: jest.fn() | |
} | |
// Testing mounting logic and inital render | |
const component = renderer.create(<Viewport target={target} />) | |
expect(component.toJSON()).toMatchSnapshot() | |
const instance = component.getInstance() | |
expect(instance.state).toEqual({ innerHeight: 600, innerWidth: 800 }) | |
expect(target.addEventListener).toHaveBeenCalled() | |
// Test the browser handles resize correctly | |
target.innerHeight = 720 | |
target.innerWidth = 1080 | |
instance.handleResize() | |
expect(instance.state).toEqual({ innerHeight: 720, innerWidth: 1080 }) | |
expect(component.toJSON()).toMatchSnapshot() | |
// Component should clean up after itself when unmounting | |
// passing a new component in update() will trigger unmounting on <Viewport /> | |
component.update(<span />) | |
expect(component.toJSON()).toMatchSnapshot() | |
expect(target.removeEventListener).toHaveBeenCalled() | |
}) |
This file contains hidden or 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 { Component } from 'react' | |
export default class Viewport extends Component { | |
static defaultProps = { | |
target: window | |
} | |
state = { | |
height: this.props.target.innerHeight, | |
width: this.props.target.innerWidth | |
} | |
handleResize = () => | |
this.setState({ | |
height: this.props.target.innerHeight, | |
width: this.props.target.innerWidth | |
}) | |
componentDidMount() { | |
window.addEventListener('resize', this.handleResize) | |
} | |
componentWillUnmount() { | |
window.removeEventListener('resize', this.handleResize) | |
} | |
render() { | |
return ( | |
<div style={{ height: this.state.height, width: this.state.width }}> | |
{this.props.children} | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment