Skip to content

Instantly share code, notes, and snippets.

@adamjarling
Last active July 25, 2023 08:12
Show Gist options
  • 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
};
}
@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