React + TS + Jestでreact-routerのテストを書く

確認環境

  • historyのバージョンとreact-router-domのバージョンが上手く噛み合ってないと既存実装で型エラーが出る可能性がある
Env Ver
react 17.0.2
react-dom 17.0.2
react-router-dom 5.2.0
react-scripts 4.0.3
typescript 4.2.3
history 4.10.1

サンプルコード

  • ToPageに飛ばしたlocation.stateを検査する内容

ToPage.tsx

export const ToPage = () => {
  const location = useLocation<{ test?: string }>();
  return <p>from {location.state?.test ?? 'nothing'}</p>;
};

ToPage.spec.tsx

const renderWithRouter = (ui: JSX.Element, { route = '/' } = {}) => {
  window.history.pushState({}, 'Test page', route);

  return render(ui, { wrapper: BrowserRouter });
};

describe('onload', () => {
  it('from history.push', () => {
    const history = createMemoryHistory<{ test: string }>();
    history.push(AppRoute.to.path, { test: 'foo' });
    const { container } = renderWithRouter(
      <Router history={history}>
        <ToPage />
      </Router>
    );

    expect(container).toHaveTextContent('from foo');
    expect(history.location.state.test).toBe('foo');
  });
});