Tengo un onEnter definido en mi contenedor de rutas y estoy tratando de descubrir cómo escribir algunas pruebas para esto;
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> ); } }Escribir una prueba para montar el componente fue bastante fácil;
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(); }); }); Pero no sé cómo probar realmente que checkAuth se invoca y realmente realiza la llamada de replace correctamente (y hace lo correcto).
Estoy seguro de que esto es trivial, pero Google me falla hasta ahora. Cualquier ejemplo/indicador sería apreciado.
Puede crear un archivo separado con su devolución de llamada onEnter y probarlo allí. Estoy llamando a esos archivos guards . Su protección raíz se verá, por ejemplo, así:
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'); } } }y la ruta:
<Route onEnter={rootGuard(this.store)} path='/' component={App}>