Last active
July 25, 2023 08:12
-
-
Save adamjarling/9ac59f3f8984c4c19d34018ee8a0401c to your computer and use it in GitHub Desktop.
Testing Library renderWithRouter helper function
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
// https://testing-library.com/docs/example-react-router | |
import React from "react"; | |
import { Router } from "react-router-dom"; | |
import { render } from "@testing-library/react"; | |
import { createMemoryHistory } from "history"; | |
// test utils file | |
function renderWithRouter( | |
ui, | |
{ | |
route = "/", | |
history = createMemoryHistory({ initialEntries: [route] }) | |
} = {} | |
) { | |
return { | |
...render(<Router history={history}>{ui}</Router>), | |
history | |
}; | |
} |
would it be possible to include a typescript binding too?
You could do something like this:
// setupTests.tsx
import React from 'react';
import { Router } from 'react-router-dom';
import { render } from '@testing-library/react';
import { createMemoryHistory, MemoryHistory } from 'history';
interface RenderWithRouterProps {
route?: string;
history?: MemoryHistory;
}
export const renderWithRouter = (
ui: React.ReactNode,
{ route = '/', history = createMemoryHistory({ initialEntries: [route] }) }: RenderWithRouterProps = {},
) => {
return {
...render(<Router history={history}>{ui}</Router>),
history,
};
};
notice the .tsx
extension instead of .ts
. You could also move this to a seperate renderWithRouter
util file
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If using typescript, I'm sure you could adjust this however you like? This specific approach is for a project w/o typescript.