Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
React Router PrivateRoute connected component and unit testing with Jest
import React from 'react';
import { Route, Redirect, withRouter } from 'react-router';
import { connect } from 'react-redux';
import Proptypes from 'prop-types';
export const PrivateRoute = ({ component: Component, isAuthenticated, ...rest }) => (
<Route
{...rest}
render={props => (
isAuthenticated
? <Component {...props} />
: <Redirect to={{
pathname: '/login',
state: { from: props.location }
}} />
)}
/>
);
PrivateRoute.propTypes = {
component: Proptypes.func.isRequired,
isAuthenticated: Proptypes.bool.isRequired
};
const mapStateToProps = (state) => ({
isAuthenticated: state.auth.isAuthenticated
});
export default withRouter(connect(mapStateToProps)(PrivateRoute));
import React from 'react';
import { shallow } from 'enzyme';
import { Route, Redirect } from 'react-router';
import { PrivateRoute } from './PrivateRoute';
describe('<PrivateRoute/>', () => {
it('passes props to Route component', () => {
const { wrapper } = setup({ path: '/scarif' });
expect(wrapper.find(Route).prop('path')).toBe('/scarif');
});
it('redirects unauthenticated users to login', () => {
const { wrapper } = setup();
const ComponentToRender = wrapper.prop('render');
const redirectWrapper = shallow(<ComponentToRender location="/scarif" />);
expect(redirectWrapper.find(Redirect).props()).toEqual({
push: false,
to: {
pathname: '/login',
state: { from: '/scarif' }
}
});
});
it('displays passed component to authenticated users', () => {
const { wrapper, props } = setup({ isAuthenticated: true });
const ComponentToRender = wrapper.prop('render');
const componentWrapper = shallow(<ComponentToRender location="/scarif" />);
expect(componentWrapper.is(props.component)).toBe(true);
expect(componentWrapper.props()).toEqual({
location: '/scarif'
});
});
});
function setup(customProps) {
const props = {
component: () => <h1>Hyperspace tracker</h1>,
isAuthenticated: false,
...customProps
};
const wrapper = shallow(<PrivateRoute {...props} />);
return {
wrapper,
props
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment