Skip to content

Instantly share code, notes, and snippets.

@stipsan
Last active June 17, 2017 18:07
Show Gist options
  • Save stipsan/24289d96cc38d466ff638239ba03c0c3 to your computer and use it in GitHub Desktop.
Save stipsan/24289d96cc38d466ff638239ba03c0c3 to your computer and use it in GitHub Desktop.
Testing with Jest: Tip #13
import renderer from 'react-test-renderer'
import Canvas from '../Canvas'
it('should render correctly', () => {
const component = renderer.create(<Form x={0} y={0} />)
expect(component.toJSON()).toMatchSnapshot()
const instance = component.getInstance()
const spy = jest.spyOn(instance, 'calculateGrid')
// shouldComponentUpdate should stop the render and thus calculateGrid shouldn't be called
component.update(<Form x={0} y={0} />)
expect(spy).not.toHaveBeenCalled()
// now the calculateGrid should've be called since x & y have new values
component.update(<Form x={2} y={2} />)
expect(spy).toHaveBeenCalled()
})
import { Component } from 'react'
export default class Canvas extends Component {
calculateGrid = () => {
/* Expensive method called during render */
}
shouldComponentUpdate({ x: nextX, y: nextY }) {
const { x: prevX, y: prevY } = this.props
return prevX !== nextX || prevY !== nextY
}
render() {
/* some typical render logic here */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment