gpt4 book ai didi

javascript - 我如何在 React Router DOM v6 上使用 MemoryRouter 测试位置?

转载 作者:行者123 更新时间:2023-12-05 08:04:03 34 4
gpt4 key购买 nike

将 React Router DOM (v6) 与 React 测试库结合使用,我想知道是否有办法处理来自 createMemoryHistory 的“模拟”历史记录或类似的替代方法。

基于Testing Library的例子,我可以在 Router 组件上模拟历史,但在 v6 中,这个组件不再接受 history 属性。

所以,我的疑问是:如何使用 React Router DOM v6 使用 RTL(React 测试库)测试历史记录和位置?我应该继续使用 MemoryRouter 吗?

最佳答案

使用 React Router DOM v6.4.0 的推荐测试方法依赖于 createMemoryRouter,它将返回一个 RemixRouter。不是通过 createMemoryHistory 使用 history,而是可以使用来自 createMemoryRouter 的 Router 的 state 对象,因为这个 Router uses its own history in memorystate 对象包含我们可以检查正确导航的位置。

使用来自 React Router DOM 的 RouterProvider,我们可以将由 createMemoryRouter 制作的路由器传递给提供者并连同我们的测试。

import { render, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import {
createMemoryRouter,
RouterProvider,
useNavigate,
} from 'react-router-dom'
import { screen } from '@testing-library/react'

// The element we want to render. Uses the hook useNavigate to send us somewhere.
const ElementToRender: React.FC = () => {
const navigate = useNavigate()

return <button onClick={() => navigate('/')}>Navigate to Home</button>
}

const setupMyTest = () => {
const router = createMemoryRouter(
[
{
path: '/',
element: <>Navigated from Start</>,
},
{
path: '/starting/path',
// Render the component causing the navigate to '/'
element: <ElementToRender />,
},
],
{
// Set for where you want to start in the routes. Remember, KISS (Keep it simple, stupid) the routes.
initialEntries: ['/starting/path'],
// We don't need to explicitly set this, but it's nice to have.
initialIndex: 0,
}
)

render(<RouterProvider router={router} />)

// Objectify the router so we can explicitly pull when calling setupMyTest
return { router }
}

it('tests react router dom v6.4.0 navigates properly', async () => {
const { router } = setupMyTest()

// Given we do start where we want to start
expect(router.state.location.pathname).toEqual('/starting/path')

// Navigate away from /starting/path
userEvent.click(screen.getByRole('button', { name: 'Navigate to Home' }))

// Don't forget to await the update since not all actions are immediate
await waitFor(() => {
expect(router.state.location.pathname).toEqual('/')
})
})

关于javascript - 我如何在 React Router DOM v6 上使用 MemoryRouter 测试位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70313688/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com