2017-01-28 4 views
1

У меня есть onEnter, определенный в контейнере маршрутов, и я пытаюсь выяснить, как написать для этого несколько тестов;Тестирование onEnter в response-redux-router

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> 
     ); 
    } 
} 

Написание теста для монтажа компонента было достаточно простым;

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(); 
    }); 
}); 

Но я в растерянности, как на самом деле проверить, что checkAuth вызывается и фактически выполняет replace вызов правильно (и делает правильные вещи).

Я уверен, что это тривиально, но google не удалось мне до сих пор. Любые примеры/указатели будут оценены.

ответ

0

Вы можете создать отдельный файл с обратным вызовом onEnter и протестировать его там. Я звоню в такие файлы guards. Корневой охранник будет выглядеть, например, так:

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'); 
     } 
    } 
} 

и маршрут:

<Route onEnter={rootGuard(this.store)} path='/' component={App}> 
Смежные вопросы