Last active
August 17, 2016 17:51
-
-
Save alicekao/8d05834952ae8cb161873b3dbeeb58ee to your computer and use it in GitHub Desktop.
Using enzyme to test react components
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
// Header component to test in header.js | |
import React, {Component} from 'react'; | |
import { Link } from 'react-router'; | |
export class Header extends Component { | |
render() { | |
const { logoutUser } = this.props; | |
return ( | |
<nav className="navbar navbar-light"> | |
<Link className='navbar-brand' to="/">PinPointMe</Link> | |
<ul className='nav navbar-nav'> | |
<li className='nav-item pull-right'> | |
<a href="#" className='nav-link' onClick={ logoutUser }>Sign out</a> | |
</li> | |
</ul> | |
</nav> | |
); | |
} | |
} | |
// Unit tests for header component in header.spec.js | |
import React from 'react'; | |
import expect, { createSpy } from 'expect'; | |
import { shallow } from 'enzyme'; | |
import { Header } from './header'; | |
import { Link } from 'react-router'; | |
describe('Header', () => { | |
it('Should have nav items of home, nav, and sign out', () => { | |
const wrapper = shallow(<Header isAuth={ true } />); // Shallow rendering of header component | |
expect(wrapper.containsMatchingElement(<Link to="/">PinPointMe</Link>)).toBe(true); | |
expect(wrapper.find('nav').length).toEqual(1); // Can find nodes within the component | |
expect(wrapper.find('.nav-link').html().includes('Sign out')).toBe(true); // Can find classnames | |
}); | |
it('Should handle logout', () => { | |
const spy = createSpy(); // Create a spy using the expect library | |
const wrapper = shallow(<Header logoutUser={spy}/>); | |
wrapper.find('a').simulate('click'); | |
expect(spy).toHaveBeenCalled(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment