我想测试从 /
路径到语言环境路径(例如 /en
)的重定向。所以这就是组件的样子:
// GuessLocale is imported from a helper
const App = () => (
<Router>
<Switch>
<Route exact path='/' render={() => (
<Redirect to={`/${guessLocale()}`} />
)} />
<Route exact path='/:lang' component={Home} />
</Switch>
</Router>
)
这是当前的测试函数:
it('redirects to a localed path', () => {
const wrapper = mount(
<MemoryRouter initialEntries={['/']}>
<App />
</MemoryRouter>
)
expect(wrapper.find('Redirect')).toHaveLength(1)
})
很明显,测试失败了,因为 Redirect 组件作为 Route
的 render
属性的函数在子组件中
在测试中,我将 App 包装在内存路由器中,但在 App 组件中,浏览器路由器已经存在,因此我可能需要重构它。
但即使在 Routes 组件中拆分了路由,我也不知道如何在 render
prop 中进行测试。
最佳答案
您可以通过检查重定向后应呈现的组件来测试它,在本例中为 Home
像这样的组件:
it('redirects to a localed path', () => {
let wrapper = mount(
<MemoryRouter initialEntries={['/']}>
<Switch>
<Route exact path='/' render={() => (
<Redirect to={`/en`} />
)} />
<Route path='/en' component={Home} />
<Route render={() => "not found"} />
</Switch>
</MemoryRouter>
)
expect(wrapper.find(Home)).toHaveLength(1)
})
我不得不删除 <Router>
让它工作,因为我们没有将它用于浏览器。另一种方法是检查 <Route>
位置 Prop 中的路径名属性。看这里:
it('redirects to a localed path', () => {
let wrapper = mount(
<MemoryRouter initialEntries={['/']}>
<Switch>
<Route exact path='/' render={() => (
<Redirect to={`/en`} />
)} />
<Route path='/en' component={Home} />
<Route render={() => "not found"} />
</Switch>
</MemoryRouter>
)
expect(wrapper.find("Route").prop('location').pathname).to.equal("/en")
})
关于javascript - React-router:用 enzyme 在 `render` prop 内部测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51244402/