这是我的testing-library-utils.js
:
import React from "react";
import { render as rtlRender } from "@testing-library/react";
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import thunk from "redux-thunk";
import reducer from "../reducers/rootReducer";
import { createMemoryHistory } from "history";
import { Router } from "react-router-dom";
const middleware = [thunk];
const history = createMemoryHistory();
function render(
ui,
{
initialState,
store = createStore(
reducer,
initialState,
composeWithDevTools(applyMiddleware(...middleware))
),
...renderOptions
} = {}
) {
function Wrapper({ children }) {
return (
<Provider store={store}>
<Router history={history}>{children}</Router>
</Provider>
);
}
return rtlRender(ui, { wrapper: Wrapper, ...renderOptions });
}
// re-export everything
export * from "@testing-library/react";
// override render method
export { render };
当我单击<Link/>
(使用userEvent(时,它不会导航到所需的页面。我想这就是我在testing-library-utils.js
中使用<Router/>
的方式。
我应该如何使用react redux和react router进行渲染,以便使用react测试库进行测试?
以下是如何在TypeScript:中执行此操作
import { MemoryRouter } from "react-router-dom";
import { render } from "@testing-library/react";
import { Provider } from "react-redux";
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import reducer from "../reducers/rootReducer";
const middleware = [thunk];
export const renderWithRouterAndRedux = (
component: React.ReactElement,
{ initialState = {}, store = createStore(reducer, initialState, applyMiddleware(...middleware)), route = "/", ...renderOptions } = {},
) => {
window.history.pushState({}, "Initial Page", route);
const Wrapper: React.FC = ({ children }) => (
<Provider store={store}>
<MemoryRouter>{children}</MemoryRouter>
</Provider>
);
return render(component, { wrapper: Wrapper, ...renderOptions });
};
// re-export everything
export * from "@testing-library/react";
// override render method
export { render };