Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save RobinHerbots/c7963c22126857201be430775809675e to your computer and use it in GitHub Desktop.
Save RobinHerbots/c7963c22126857201be430775809675e to your computer and use it in GitHub Desktop.
Example of a Testing Library renderWith helper function to include React Router match object in tests
// Component example
// ContentWrapper.jsx
import React from "react";
import Main from "./Main";
import { withRouter } from "react-router-dom";
const ContentWrapper = ({ children, match }) => (
<Main>
<p>Match id: {match.params.id}</p>
{children}
</Main>
);
export default withRouter(ContentWrapper);
//Test file
// Helper function
export function renderWithRouterMatch(
ui,
{
path = "/",
route = "/",
history = createMemoryHistory({ initialEntries: [route] })
} = {}
) {
return {
...render(
<Router history={history}>
<Route path={path} component={ui} />
</Router>
)
};
}
// ContentWrapper.test.js
import React from "react";
import ContentWrapper from "./ContentWrapper";
import "@testing-library/jest-dom/extend-expect";
it("mocks match.params in the test in case your component references match.params.someValueHere", () => {
const { getByText } = renderWithRouterMatch(ContentWrapper, {
route: "/project/ABC123",
path: "/project/:id"
});
expect(getByText("Match id: ABC123")).toBeInTheDocument();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment