2
0

test-router.tsx 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import { ReactNode } from 'react';
  2. import { MemoryRouter, Routes, Route, useLocation } from 'react-router-dom';
  3. import { vi } from 'vitest';
  4. /**
  5. * 测试路由器的包装组件
  6. */
  7. export function TestRouter({
  8. children,
  9. initialPath = '/',
  10. routes = []
  11. }: {
  12. children: ReactNode;
  13. initialPath?: string;
  14. routes?: Array<{ path: string; element: ReactNode }>;
  15. }) {
  16. return (
  17. <MemoryRouter initialEntries={[initialPath]}>
  18. <Routes>
  19. {routes.map((route, index) => (
  20. // @ts-ignore
  21. <Route key={index} path={route.path} element={route.element} />
  22. ))}
  23. {/* @ts-ignore */}
  24. <Route path="*" element={children} />
  25. </Routes>
  26. </MemoryRouter>
  27. );
  28. }
  29. /**
  30. * 获取当前路由位置的Hook
  31. */
  32. export function useTestLocation() {
  33. const location = useLocation();
  34. return location;
  35. }
  36. /**
  37. * 创建测试导航函数
  38. */
  39. export function createTestNavigation() {
  40. return {
  41. navigate: vi.fn(),
  42. goBack: vi.fn(),
  43. goForward: vi.fn(),
  44. replace: vi.fn()
  45. };
  46. }