2017-01-28 45 views
1

私のルートコンテナにonEnterが定義されていますが、これについていくつかのテストを書く方法を理解しようとしています。react-redux-routerでonEnterをテストする

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}> 
あなたのルートガードは、このような例を探します
関連する問題