Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

255
Visualizações
Testing onEnter in react-redux-router

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.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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}>
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda