3Do*_*Dos 5 javascript reactjs jestjs react-router enzyme
我想测试从/
路径到语言环境路径的重定向(例如/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>
)
Run Code Online (Sandbox Code Playgroud)
这是当前的测试功能:
it('redirects to a localed path', () => {
const wrapper = mount(
<MemoryRouter initialEntries={['/']}>
<App />
</MemoryRouter>
)
expect(wrapper.find('Redirect')).toHaveLength(1)
})
Run Code Online (Sandbox Code Playgroud)
显然,该测试失败了,因为Redirect组件位于一个子对象中,而该组件作为render
prop 的功能。Route
在测试中,我将App封装在内存路由器中,但是在App组件中,已经存在浏览器路由器,因此我可能需要对其进行重构。
但是即使在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)
})
Run Code Online (Sandbox Code Playgroud)
我必须删除<Router>
才能使其正常工作,因为我们不将它用于浏览器。另一种方法是检查<Route>
location 属性中的路径名属性。看这里:
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")
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1367 次 |
最近记录: |