如何模拟 react-hooks-testing-library 的 useRouter 参数?
How to mock useRouter parameters for react-hooks-testing-library?
我有一个自定义挂钩,其结构为:
const urlHook = () => {
const router = useRouter();
const read = () => {
return validate(router.query.param);
}
const write = (params) => {
router.push(
{
query: {
param: params,
},
},
undefined,
{shallow: true},
)
}
const validate = (params) => {}
}
我想使用 react-hooks-testing-library
测试此挂钩,但我不确定如何设置 router.query.param
以读取我想要的值或如何检查函数 write()
是否会创建正确的 url?
模拟整个钩子 - jest.requireActual
:
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useParams: () => ({
blogId: 'company1',
articleId: 'blog1',
}),
useRouteMatch: () => ({ url: '/blog/blog1/article/article1' }),
}));
模拟 history/routing 状态 - MemoryRouter:
import {Route, MemoryRouter} from 'react-router-dom';
...
const renderWithRouter = ({children}) => (
render(
<MemoryRouter initialEntries={['blogs/1']}>
<Route path='blogs/:blogId'>
{children}
</Route>
</MemoryRouter>
)
)
我有一个自定义挂钩,其结构为:
const urlHook = () => {
const router = useRouter();
const read = () => {
return validate(router.query.param);
}
const write = (params) => {
router.push(
{
query: {
param: params,
},
},
undefined,
{shallow: true},
)
}
const validate = (params) => {}
}
我想使用 react-hooks-testing-library
测试此挂钩,但我不确定如何设置 router.query.param
以读取我想要的值或如何检查函数 write()
是否会创建正确的 url?
模拟整个钩子 - jest.requireActual
:
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useParams: () => ({
blogId: 'company1',
articleId: 'blog1',
}),
useRouteMatch: () => ({ url: '/blog/blog1/article/article1' }),
}));
模拟 history/routing 状态 - MemoryRouter:
import {Route, MemoryRouter} from 'react-router-dom';
...
const renderWithRouter = ({children}) => (
render(
<MemoryRouter initialEntries={['blogs/1']}>
<Route path='blogs/:blogId'>
{children}
</Route>
</MemoryRouter>
)
)