Skip to content

Instantly share code, notes, and snippets.

@adamjarling
Last active July 25, 2023 08:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adamjarling/9ac59f3f8984c4c19d34018ee8a0401c to your computer and use it in GitHub Desktop.
Save adamjarling/9ac59f3f8984c4c19d34018ee8a0401c to your computer and use it in GitHub Desktop.
Testing Library renderWithRouter helper function
// 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
};
}
@timrobinson33
Copy link

would it be possible to include a typescript binding too?

@adamjarling
Copy link
Author

If using typescript, I'm sure you could adjust this however you like? This specific approach is for a project w/o typescript.

@lextas
Copy link

lextas commented Aug 12, 2020

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