在react-redux-router中测试onEnter

时间:2017-01-28 22:26:09

标签: reactjs redux jestjs enzyme react-router-redux

我的路由容器中定义了一个onEnter,我正在试图弄清楚如何为此编写一些测试;

with j ( tr_id, tr_item_id, parent_lookup_type, item_desc ) as (
         select t.tr_id, t.tr_item_id, substr(t.tr_item_id, 1, 3), i.item_desc
         from   tr t left outer join item i on t.tr_item_id = i.item_id
       )
select  tr_id, tr_item_id, tr_item_id as child_lookup_type, parent_lookup_type,
        tr_item_id as item_id, item_desc
  from  j
  where j.item_desc is not null
union all
select  j.tr_id, j.tr_item_id, null, j.parent_lookup_type, j.parent_lookup_type,
        i.item_desc
  from  j left outer join item i on j.parent_lookup_type = i.item_id
  where j.item_desc is null
;

编写测试来安装组件非常简单;

select a.*, b.*, c.* 
from a
left join b
 on a.cola=b.cola
and a.colb = b.colb
left join c
 on a.cola=c.cola
and a.colb=c.colb

但我对如何实际测试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(); }); }); 调用(并呈现正确的东西)感到茫然。

我确定这是微不足道的,但到目前为止谷歌让我失望了......任何例子/指针都会受到赞赏。

1 个答案:

答案 0 :(得分: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}>