Forked from adamjarling/renderWithRouterMatchExample.js
Created
December 6, 2022 07:39
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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