我正在尝试设置一个测试文件以在我的应用程序上呈现路由/页面。我正在尝试用 Redux 和 Router 包装所有东西,这就是我所拥有的:
import React from 'react';
import { render } from 'react-testing-library';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import reducer from '../../store/reducer';
import {Link, Route, Router, Switch} from 'react-router-dom'
import {createMemoryHistory} from 'history'
import ViewNode from '../Pages/ViewNode';
const customRender = (
ui,
{
route = '/',
history = createMemoryHistory({ initialEntries: [route] }),
initialState,
store = createStore(reducer, initialState),
...options
} = {}
) => ({
...render(
<Provider store={store}>
<Router history={history}>{ui}</Router>
</Provider>,
options
),
history,
});
test('can render with redux and router', () => {
const { getByTestId } = customRender(
<Route path="/server/:env/:nodeName">
<ViewNode />
</Route>,
{
route: '/server/prod/some.server.name.com',
}
);
expect(getByTestId('page-content')).toBeVisible()
})
然后我收到以下错误:
Error: Uncaught [TypeError: Cannot read property 'params' of undefined]
抛出错误的原因是它找不到 React Router 参数。当我初始化状态时,它在组件构造函数中失败:
this.state = {
modal: false,
activeTab: '1',
imageStatus: "loading",
env: props.match.params.env, //failing here
nodeName: props.match.params.nodeName,
environments: props.environments,
}
似乎我上面的实现没有正确包装路由器。
我将如何使用 Redux 和 Router 正确包装我的页面组件,以便它可以获取这些路由器参数?