【发布时间】:2020-10-22 01:46:14
【问题描述】:
我正在尝试为 react 组件创建一个单元测试,其中组件的 props 检查部分 url 路径以确定操作过程,并在路径的末尾接收参数或值。
使用https://testing-library.com/docs/example-reach-router 中给出的示例,我创建了自己的单元测试,但是当我运行测试时,我的组件抱怨 uri 值不存在。另外,当我将 console.log(props) 添加到我的组件并再次运行测试时,props 是未定义的。
我尝试了一种使用 LocationProvider 包装组件的变体,如 https://reach.tech/router/api/LocationProvider 所示添加历史记录
相关代码sn-p为-
function renderWithRouter(
ui,
{ route = '/', history = createHistory(createMemorySource(route)) } = {}
) {
return {
...render(
<LocationProvider history={history}>{ui}</LocationProvider>
)
,
history,
}
}
describe('View Order Test', () => {
describe('Order', () => {
it('Renders the Order View for a specific Order', async () => {
const { queryByText } =
renderWithRouter(
<State initialState={initialState} reducer={reducer}>
<ViewOrder />
</State>
, { route: '/order/orderView/1234', }
)
expect(queryByText('OrderID: 1234'))
}
)
})
似乎没有任何效果。有没有办法将道具传递给一个单元中的 uri (@reach/router) 组件?正如我所说,我的单位是上面给出的那些的副本
【问题讨论】:
-
很难按原样提供帮助,您能在代码盒中重现吗?
-
将整个代码放在那里会太多,但我可以向您保证,我基本上复制了链接中的内容
-
你不需要放所有代码,只是一个最小的可复现的例子
-
添加相关代码片段
标签: reactjs react-testing-library reach-router