find-menu-by-path.test.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import { describe, expect, it } from 'vitest';
  2. import { findMenuByPath, findRootMenuByPath } from './find-menu-by-path';
  3. // 示例菜单数据
  4. const menus: any[] = [
  5. { path: '/', children: [] },
  6. { path: '/about', children: [] },
  7. {
  8. path: '/contact',
  9. children: [
  10. { path: '/contact/email', children: [] },
  11. { path: '/contact/phone', children: [] },
  12. ],
  13. },
  14. {
  15. path: '/services',
  16. children: [
  17. { path: '/services/design', children: [] },
  18. {
  19. path: '/services/development',
  20. children: [{ path: '/services/development/web', children: [] }],
  21. },
  22. ],
  23. },
  24. ];
  25. describe('menu Finder Tests', () => {
  26. it('finds a top-level menu', () => {
  27. const menu = findMenuByPath(menus, '/about');
  28. expect(menu).toBeDefined();
  29. expect(menu?.path).toBe('/about');
  30. });
  31. it('finds a nested menu', () => {
  32. const menu = findMenuByPath(menus, '/services/development/web');
  33. expect(menu).toBeDefined();
  34. expect(menu?.path).toBe('/services/development/web');
  35. });
  36. it('returns null for a non-existent path', () => {
  37. const menu = findMenuByPath(menus, '/non-existent');
  38. expect(menu).toBeNull();
  39. });
  40. it('handles empty menus list', () => {
  41. const menu = findMenuByPath([], '/about');
  42. expect(menu).toBeNull();
  43. });
  44. it('handles menu items without children', () => {
  45. const menu = findMenuByPath(
  46. [{ path: '/only', children: undefined }] as any[],
  47. '/only',
  48. );
  49. expect(menu).toBeDefined();
  50. expect(menu?.path).toBe('/only');
  51. });
  52. it('finds root menu by path', () => {
  53. const { findMenu, rootMenu, rootMenuPath } = findRootMenuByPath(
  54. menus,
  55. '/services/development/web',
  56. );
  57. expect(findMenu).toBeDefined();
  58. expect(rootMenu).toBeUndefined();
  59. expect(rootMenuPath).toBeUndefined();
  60. expect(findMenu?.path).toBe('/services/development/web');
  61. });
  62. it('returns null for undefined or empty path', () => {
  63. const menuUndefinedPath = findMenuByPath(menus);
  64. const menuEmptyPath = findMenuByPath(menus, '');
  65. expect(menuUndefinedPath).toBeNull();
  66. expect(menuEmptyPath).toBeNull();
  67. });
  68. it('checks for root menu when path does not exist', () => {
  69. const { findMenu, rootMenu, rootMenuPath } = findRootMenuByPath(
  70. menus,
  71. '/non-existent',
  72. );
  73. expect(findMenu).toBeNull();
  74. expect(rootMenu).toBeUndefined();
  75. expect(rootMenuPath).toBeUndefined();
  76. });
  77. });