Created
June 7, 2018 10:27
-
-
Save clodal/0a9239f0030c644d6283186bdd635a39 to your computer and use it in GitHub Desktop.
React Unit Tests: Jest + Enzyme Basic Patterns
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 React from 'react' | |
import { Icon, Button, Segment } from 'semantic-ui-react' | |
class Bar extends React.Component { | |
state = { | |
isCool: false, | |
} | |
toggleCool = () => this.setState({ isCool: !this.state.isCool }) | |
render() { | |
const { isCool } = this.state | |
const { children, onClick: handleClick } = this.props | |
return ( | |
<Segment basic> | |
<h1>I am a {isCool ? 'Cool' : ''} Bar</h1> | |
<Icon name='home' /> | |
<Button onClick={handleClick}>Click me</Button> | |
<Button onClick={this.toggleCool}>Toggle coolness</Button> | |
{children} | |
</Segment> | |
) | |
} | |
} | |
export default Bar |
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 React from 'react' | |
import { shallow, mount } from 'enzyme' | |
import renderer from 'react-test-renderer' | |
import Bar from './Bar' | |
describe('<Bar />', () => { | |
it('renders correctly', () => { | |
const tree = renderer.create(<Bar />).toJSON() | |
expect(tree).toMatchSnapshot() | |
}) | |
it('renders components', () => { | |
const wrapper = shallow(<Bar />) | |
expect(wrapper.length).toBe(1) | |
}) | |
it('renders an `.icon`', () => { | |
const wrapper = mount(<Bar />) | |
expect(wrapper.find('.icon').length).toBe(1) | |
}) | |
it('renders children when passed in', () => { | |
const wrapper = shallow(( | |
<Bar> | |
<div className='unique' /> | |
</Bar> | |
)) | |
expect(wrapper.contains(<div className='unique' />)).toEqual(true) | |
}) | |
it('has basic prop', () => { | |
const wrapper = shallow(<Bar />) | |
expect(wrapper.prop('basic')).toEqual(true) | |
}) | |
it('simulates click events', () => { | |
const onButtonClick = jest.fn() | |
const wrapper = mount(<Bar onClick={onButtonClick} />) | |
wrapper.find('button').at(0).simulate('click') | |
expect(onButtonClick.mock.calls.length).toEqual(1) | |
}) | |
it('should have correct default state', () => { | |
const wrapper = shallow(<Bar />) | |
expect(wrapper.state().isCool).toEqual(false) | |
}) | |
it('should handle state changes', () => { | |
const wrapper = mount(<Bar />) | |
expect(wrapper.state().isCool).toEqual(false) | |
const toggleButton = wrapper.find('button').at(1); | |
toggleButton.simulate('click') | |
expect(wrapper.state().isCool).toEqual(true) | |
}) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment