Reputation: 5293
So I created a RestrictedRoute
component based on Route
from react-router (v4)
and using branch
method from recompose
:
import React from 'react';
import { connect } from 'react-redux';
import { compose, branch, renderComponent } from 'recompose';
import { Route, Redirect } from 'react-router-dom';
const RestrictedRoute = (props) => {
const { component, ...otherProps } = props;
return <Route {...otherProps} component={component} />;
};
const mapStateToProps = state => ({
authenticated: state.authentication.session,
});
const branched = branch(
({ authenticated }) => !authenticated,
renderComponent(() => <Redirect to="/" />),
);
const enhanced = compose(
connect(mapStateToProps),
branched,
)(RestrictedRoute);
export default enhanced;
It works perfectly fine but now I need to write some tests that will tell me if the redirect is working properl, so I did this:
import React from 'react';
import { shallow } from 'enzyme';
import { Provider } from 'react-redux';
import { Redirect, MemoryRouter } from 'react-router-dom';
import configureStore from 'redux-mock-store';
import RestrictedRoute from '../RestrictedRoute';
import { initialAuthenticationState } from 'Reducers/authentication';
describe('<RestrictedRoute />', () => {
const mockStore = configureStore();
let store;
let container;
beforeEach(() => {
store = mockStore({
authentication: { ...initialAuthenticationState }, // authentication.session is false in the initialAuthenticationState
});
container = shallow(
<MemoryRouter>
<Provider store={store}>
<RestrictedRoute />
</Provider>,
</MemoryRouter>
);
})
test('redirects if not authenticated', () => {
expect(container.find(Redirect).length).toBe(1);
});
});
I get the following results, which is not what I expected:
● <RestrictedRoute /> › redirects if not authenticated
expect(received).toBe(expected)
Expected value to be (using ===):
1
Received:
0
What am I missing?
Upvotes: 1
Views: 818
Reputation: 5293
The problem was with the shallow
. I shouldn't have used it because it is not its purpose. mount
was the function I was looking for.
Upvotes: 2