从 React 中的两个测试库渲染助手组成单个渲染助手
Compose single render helper from two testing library render helpers in React
干杯。关于使用 @testing-library/react
和创建类似于下面的渲染助手的快速问题。
const renderWithRouter = (
ui,
{
route = '/',
history = createMemoryHistory({ initialEntries: [route] })
} = {}
) => {
const Wrapper = ({ children }) => (
<Router history={history}>{children}</Router>
);
return {
...render(ui, { wrapper: Wrapper }),
history
};
};
const renderWithRedux = (
ui,
{
initialState = {},
reducer = {},
store = createStore(reducer, initialState)
} = {}
) => {
const Wrapper = ({ children }) => (
<Provider store={store}>{children}</Provider>
);
return {
...render(ui, { wrapper: Wrapper }),
store
};
};
如何将上面的方法更改为可组合的,如下所示?
const render = renderWithRouter(renderWithRedux(<Component />,{...}),{...});
据我所知,我不能只从渲染中获取原始 UI 元素。我目前正在考虑另一种选择。 Answers/ideas 非常感谢并提前致谢。
您可以创建一个新方法来使用 Router 和 Redux 进行渲染:
const renderWithRouterAndRedux = (
ui,
{
route = '/',
history = createMemoryHistory({ initialEntries: [route] }),
initialState = {},
reducer = {},
store = createStore(reducer, initialState),
} = {}
) => {
const Wrapper = ({ children }) => (
<Provider store={store}>
<Router history={history}>{children}</Router>
</Provider>
);
return {
...render(ui, { wrapper: Wrapper }),
history,
store,
};
};
如果你想更灵活一些,我写了一个小库可以做到这一点:https://github.com/Gpx/render-composer。
干杯。关于使用 @testing-library/react
和创建类似于下面的渲染助手的快速问题。
const renderWithRouter = (
ui,
{
route = '/',
history = createMemoryHistory({ initialEntries: [route] })
} = {}
) => {
const Wrapper = ({ children }) => (
<Router history={history}>{children}</Router>
);
return {
...render(ui, { wrapper: Wrapper }),
history
};
};
const renderWithRedux = (
ui,
{
initialState = {},
reducer = {},
store = createStore(reducer, initialState)
} = {}
) => {
const Wrapper = ({ children }) => (
<Provider store={store}>{children}</Provider>
);
return {
...render(ui, { wrapper: Wrapper }),
store
};
};
如何将上面的方法更改为可组合的,如下所示?
const render = renderWithRouter(renderWithRedux(<Component />,{...}),{...});
据我所知,我不能只从渲染中获取原始 UI 元素。我目前正在考虑另一种选择。 Answers/ideas 非常感谢并提前致谢。
您可以创建一个新方法来使用 Router 和 Redux 进行渲染:
const renderWithRouterAndRedux = (
ui,
{
route = '/',
history = createMemoryHistory({ initialEntries: [route] }),
initialState = {},
reducer = {},
store = createStore(reducer, initialState),
} = {}
) => {
const Wrapper = ({ children }) => (
<Provider store={store}>
<Router history={history}>{children}</Router>
</Provider>
);
return {
...render(ui, { wrapper: Wrapper }),
history,
store,
};
};
如果你想更灵活一些,我写了一个小库可以做到这一点:https://github.com/Gpx/render-composer。