I've got an onEnter defined in my routes container and I'm trying to figure out how to write some tests for this;
export default class Root extends React.Component<IRootProps, void> {
store: Redux.Store<IAppState> = configureStore();
history: ReactRouterReduxHistory = syncHistoryWithStore(hashHistory, this.store);
checkAuth = (nextState: RouterState, replace: RedirectFunction): void => {
console.log(this.store.getState().authToken);
if (nextState.location.pathname !== '/login') {
if (this.store.getState().authToken) {
if (nextState.location.state && nextState.location.pathname) {
replace(nextState.location.pathname);
}
} else {
replace('/login');
}
}
}
render() {
return (
<Provider store={this.store}>
<div>
<Router history={this.history}>
<Route path='/login' component={Login}/>
<Route onEnter={this.checkAuth} path='/' component={App}>
<IndexRoute component={Counter}/>
</Route>
</Router>
<DevTools />
</div>
</Provider>
);
}
}
Writing a test to mount the component was easy enough;
function setup() {
const middlewares: any[] = [];
const mockStore = configureStore(middlewares);
const initialState = {};
const store:any = mockStore(initialState);
const component = mount(<Root store={store as Store<IAppState>} />);
return {
component: component,
history: history
};
}
describe('Root component', () => {
it('should create the root component', () => {
const {component, history} = setup();
expect(component.exists()).toBeTruthy();
});
});
But I'm at a loss for how to actually test that checkAuth is invoked and actually performs the replace call correctly (and renders the right thing).
I'm sure this is trivial but google fails me so far.. Any examples/pointers would be appreciated.
You can create a separate file with your onEnter callback and test it there. I am calling such files guards. Your root guard will look for example like this:
export default (store: Redux.Store<IAppState>) => (nextState: RouterState, replace: RedirectFunction): void => {
if (nextState.location.pathname !== '/login') {
if (store.getState().authToken) {
if (nextState.location.state && nextState.location.pathname) {
replace(nextState.location.pathname);
}
} else {
replace('/login');
}
}
}
and the route:
<Route onEnter={rootGuard(this.store)} path='/' component={App}>