-
-
Save oieduardorabelo/7a4a977742dc13355334f50213c87c73 to your computer and use it in GitHub Desktop.
Testando com Jest: Dica #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() | |
} | |
// Testando lógica do cicle de vida da | |
// montagem e renderização do componente | |
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() | |
// Imitando o "resize" do navegador | |
target.innerHeight = 720 | |
target.innerWidth = 1080 | |
instance.handleResize() | |
expect(instance.state).toEqual({ innerHeight: 720, innerWidth: 1080 }) | |
expect(component.toJSON()).toMatchSnapshot() | |
// O componente deve executar a limpeza quando ele é desmontado | |
// passando um novo componente em "update()" irá desmontar | |
// o <Viewport /> atual | |
component.update(<span />) | |
expect(component.toJSON()).toMatchSnapshot() | |
expect(target.addEventListener).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