test-router.tsx 983 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. <Route key={index} path={route.path} element={route.element} />
  21. ))}
  22. <Route path="*" element={children} />
  23. </Routes>
  24. </MemoryRouter>
  25. );
  26. }
  27. /**
  28. * 获取当前路由位置的Hook
  29. */
  30. export function useTestLocation() {
  31. const location = useLocation();
  32. return location;
  33. }
  34. /**
  35. * 创建测试导航函数
  36. */
  37. export function createTestNavigation() {
  38. return {
  39. navigate: vi.fn(),
  40. goBack: vi.fn(),
  41. goForward: vi.fn(),
  42. replace: vi.fn()
  43. };
  44. }