Skip to content

Instantly share code, notes, and snippets.

@oieduardorabelo
Forked from stipsan/Canvas-test.jsx
Last active June 16, 2017 09:56
Show Gist options
  • Save oieduardorabelo/69271f42db10e8f1ecd0540a85bbb2e6 to your computer and use it in GitHub Desktop.
Save oieduardorabelo/69271f42db10e8f1ecd0540a85bbb2e6 to your computer and use it in GitHub Desktop.
Testando com Jest: Dica #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 deve evitar que o "render" seja chamando e "calculateGrid" não deve ser chamado
component.update(<Form x={0} y={0} />)
expect(spy).not.toHaveBeenCalled()
// agora "calculateGrid" deve ser chamado, já que X e Y possuem novos valores
component.update(<Form x={2} y={2} />)
expect(spy).not.toHaveBeenCalled()
})
import { Component } from 'react'
export default class Canvas extends Component {
calculateGrid = () => {
/* método expensivo chamado durante "render" */
}
shouldComponentUpdate({ x: nextX, y: nextY }) {
const { x: prevX, y: prevY } = this.props
return prevX !== nextX || prevY !== nextY
}
render() {
/* típica lógica para renderizaço do seu componente */
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment