[英]How to unit test an array as a prop using react-testing-library
[英]unit test not using url path with parameter when using reach router with react-testing-library
我正在尝试为反应组件创建一个单元测试,其中组件的道具检查 url 路径的一部分以决定行动方案,并在路径的末尾接受参数或值。
使用https://testing-library.com/docs/example-reach-router中给出的示例,我创建了自己的单元测试,但是当我运行测试时,我的组件抱怨 uri 值不存在。 此外,当我将 console.log(props) 添加到我的组件并再次运行测试时,props 是未定义的。
我尝试了一种使用 LocationProvider 包装组件的变体,如https://reach.tech/router/api/LocationProvider所示
相关的代码片段是 -
function renderWithRouter( ui, { route = '/', history = createHistory(createMemorySource(route)) } = {} ) { return {...render(
<LocationProvider history={history}>{ui}</LocationProvider>
)
,
history,
} }
describe('查看订单测试', () => {
描述('订单',()=> {
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) 组件? 正如我所说,我的单位是上面给出的那些的副本
通过添加 Reach Router 并将其包裹在组件周围来解决。
在使用 url 参数和reach-router
测试组件时,我遇到了类似的问题。
路由文件示例:
import { Router } from "@reach/router";
import Item from "pages/Item";
const Routes = () => (
<Router>
<Item path="/item/:id" />
</Router>
);
...
在我的测试代码中,我在渲染 function 中执行了此操作:
import {
Router,
createHistory,
createMemorySource,
LocationProvider,
} from "@reach/router";
import { render } from "@testing-library/react";
export function renderWithRouter(
ui,
{ route = "/", history = createHistory(createMemorySource(route)) } = {}
) {
return {
...render(
<LocationProvider history={history}>
<Router>{ui}</Router>
</LocationProvider>
),
history,
};
}
和测试用例:
test("renders the component", async () => {
renderWithRouter(<Item path="/item/:id" />, { route: "/item/1" });
...
});
通过这种方式,我能够获得 url 参数并且所有测试都运行良好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.