Last active
June 17, 2017 18:07
-
-
Save stipsan/24289d96cc38d466ff638239ba03c0c3 to your computer and use it in GitHub Desktop.
Testing with Jest: Tip #13
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 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() | |
}) |
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 { 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