Created
September 24, 2019 20:54
-
-
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
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