Skip to content

Instantly share code, notes, and snippets.

@stipsan
Last active October 17, 2021 22:13
Show Gist options
  • Save stipsan/c15af304c2cf9a0250d59092733bb43d to your computer and use it in GitHub Desktop.
Save stipsan/c15af304c2cf9a0250d59092733bb43d to your computer and use it in GitHub Desktop.
Testing with Jest: Tip #14
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()
})
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