javascript - React-router:使用酶在“渲染”道具内部进行测试
问题描述
我想测试从/
路径到语言环境路径的重定向(例如/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 组件在一个子组件中,作为一个函数作为render
prop 到Route
在测试中,我将应用程序包装在内存路由器中,但在应用程序组件中,浏览器路由器已经存在,因此我可能需要对其进行重构。
但即使将路由拆分为 Routes 组件,我也不知道如何在render
道具内部进行测试。
解决方案
您可以通过检查重定向后应该呈现的组件来测试这一点,在这种情况下,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>
location 属性中的 pathname 属性。看这里:
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")
})
推荐阅读
- java - Spring Boot 库中的可选依赖类
- matlab - 这个矩阵乘法在 MATLAB 中有意义吗?
- angular - Angular 6我不能使用带有输入标签的ngModel
- shell - Unable to Pass option using getopts to oozie shell Action
- reactjs - 我应该将所有子路由都放在其直接父级中吗?
- python - Python - 如何遍历字典以获取基于属性的访问
- c# - 在服务器上使用线程与异步编程
- node.js - 在 node.js 中进行嵌套请求调用
- python - 通过在 pandas 数据框中增加 5 对数字进行分组
- angular - 仅当主机上存在特定类时,Angular Renderer2 setStyle