2016-06-20 59 views
1

我想測試反應成分:測試反應成分withing反應路由器

export class IdentityPage extends React.Component<PageProps, State> { 
    constructor(props: PageProps) { 
     super(props); 
    } 

    componentDidMount() { this.reload(this.props.routeParams.id); } 
    render(){....} 
} 

這是在使用反應路由器這樣的:

<Router history={hashHistory}> 
    <Route path="/"> 
     <Route path="Identities"> 
      <Route path=":action/:id" component={IdentityPage} /> 
     </Route> 
    </Route> 
</Router> 

然而,測試失敗:

無法讀取的不確定

屬性 'ID' 10

,當我嘗試運行:

let pageProps: PageProps = { 
    params: { 
     action: "view", 
     id: "0" 
    } 
}; 
let instance = TestUtils.renderIntoDocument(React.createElement(IdentityPage, pageProps)); 

回答

0

我不得不改變pageProps包括routeParams:

let pageProps: PageProps = { 
    params: { action: "view", id: "0" }, 
    routeParams: { action: "view", id: "0" }, 
}; 

let instance = TestUtils.renderIntoDocument(React.createElement(IdentityPage, pageProps)); 

在頁面我只是訪問routeParams代替params

0

如果使用反應路由器V4,可以使用<MemoryRouter ...>並與<Route ...>成分包裹你的組件。

MemoryRouter讓你的「URL」記憶中的歷史(不讀取或寫入到地址欄)。在測試和非瀏覽器環境中很有用。

作爲例子(from react-router repository

<MemoryRouter initialEntries={[ '/sushi/california' ]}> 
    <Route path="/sushi/:roll" render={({ match }) => { 
    return <div>{match.url}</div> 
    }}/> 
</MemoryRouter> 

所以你的情況

let instance = TestUtils.renderIntoDocument(
    <MemoryRouter initialEntries={['view/0']}> 
    <Route path=":action/:id" component={IdentityPage} /> 
    </MemoryRouter> 
);