Skip to content

Instantly share code, notes, and snippets.

@adamjarling
Created September 24, 2019 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adamjarling/5b5f607e45d9de47f9d18423697b2535 to your computer and use it in GitHub Desktop.
Save adamjarling/5b5f607e45d9de47f9d18423697b2535 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