Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

import { ChevronRightIcon } from '@heroicons/react/24/solid'; import { isEmpty } from…

  1. User

    import { ChevronRightIcon } from '@heroicons/react/24/solid'; import { isEmpty } from 'lodash'; import { createPortal } from 'react-dom';

    import { Tooltip, TooltipContent, TooltipTrigger } from '@/common/components/tw/tooltip'; import { cn } from '@/common/util/cn'; import { GradientIconWrapper } from '@/features/navigation/sidenav/components/icons/GradientIconWrapper'; import { NavItemVariants } from '@/features/navigation/sidenav/components/variants/NavItemVariants'; import { useIsNavItemActive } from '@/features/navigation/sidenav/hook/useIsNavItemActive'; import { useSideNavigationStore } from '@/features/navigation/sidenav/hook/useSideNavigationStore'; import { IconsMap } from '@/features/navigation/sidenav/model/IconsMap'; import { SideNavItem } from '@/features/navigation/sidenav/model/SideNavItem'; import { SIDE_OFFSET } from '@/features/navigation/util/constants';

    type OnSelectCb = (navItem: SideNavItem) => void;

    type NavItemProps = { navItemConfig: SideNavItem; onSelect: OnSelectCb; asDiv?: boolean; isPressed?: boolean; };

    export const BaseNavItem = ({ navItemConfig, onSelect, asDiv, isPressed }: NavItemProps) => { const { isCollapsed } = useSideNavigationStore();

    const isActive = useIsNavItemActive(navItemConfig);

    const onSelectItem = () => { onSelect(navItemConfig); };

    // This check prevents the app from crashing when the icon is not found - case of search results containing sub items const icon: React.FC<React.SVGProps> | null = navItemConfig.icon ? IconsMap[navItemConfig.icon] : null;

    const getVariantName = () => { if (isActive) { return 'active'; } if (isPressed) { return 'pressed'; } return 'default'; };

    if (isCollapsed) { return ( <div className={cn( NavItemVariants({ size: 'icon', variant: getVariantName() }) )} onClick={onSelectItem}> {icon && }

        {createPortal(
          <TooltipContent
            side={'right'}
            className="border-none bg-navigation text-navigation-foreground"
            sideOffset={SIDE_OFFSET}>
            <p>{navItemConfig.title}</p>
          </TooltipContent>,
          document.body
        )}
      </Tooltip>
    );
    

    }

    const Element = asDiv ? 'div' : 'button';

    return ( <Element className={cn( NavItemVariants({ variant: getVariantName() }), 'w-full flex flex-1 items-center' )} onClick={onSelectItem}> {/* when search results should list the found sub items */} {icon && }

      <p className="ct-animate-fadein flex flex-1 truncate px-2 text-start">
        {navItemConfig.title}
      </p>
    
      {!isEmpty(navItemConfig.subItems) && <ChevronRightIcon className="size-4" />}
    </Element>
    

    ); }; create a test file using vitest and @testing-library/react

  2. Assistant

    Certainly! Below is an example of how you can create a test file for the BaseNavItem component using Vitest and @testing-library/react. This test suite covers rendering the component in both collapsed and expanded states, verifying the presence of icons and titles, ensuring the onSelect callback is triggered correctly, and handling tooltip functionality.

    Prerequisites

    1. Ensure you have the necessary dependencies installed:

      npm install --save-dev vitest @testing-library/react @testing-library/jest-dom @testing-library/user-event
      
    2. Configure Vitest in your project if you haven't already. Typically, you can add a vitest.config.ts or configure it in your package.json.

    Test File: BaseNavItem.test.tsx

    // BaseNavItem.test.tsx
    import React from 'react';
    import { render, screen, fireEvent } from '@testing-library/react';
    import { describe, it, expect, vi, beforeEach } from 'vitest';
    import userEvent from '@testing-library/user-event';
    import { createPortal } from 'react-dom';
    
    import { BaseNavItem } from './BaseNavItem';
    import { SideNavItem } from '@/features/navigation/sidenav/model/SideNavItem';
    
    // Mock dependencies
    vi.mock('@/features/navigation/sidenav/hook/useSideNavigationStore', () => ({
      useSideNavigationStore: () => ({
        isCollapsed: false,
      }),
    }));
    
    vi.mock('@/features/navigation/sidenav/hook/useIsNavItemActive', () => ({
      useIsNavItemActive: () => false,
    }));
    
    vi.mock('@/features/navigation/sidenav/model/IconsMap', () => ({
      IconsMap: {
        testIcon: (props: React.SVGProps<SVGSVGElement>) => (
          <svg data-testid="test-icon" {...props}>
            <circle cx="10" cy="10" r="10" />
          </svg>
        ),
      },
    }));
    
    vi.mock('@/common/util/cn', () => ({
      cn: (...classes: string[]) => classes.join(' '),
    }));
    
    vi.mock('@/features/navigation/sidenav/components/variants/NavItemVariants', () => ({
      NavItemVariants: () => 'nav-item-class',
    }));
    
    // Mock Tooltip Portal to render content directly for testing
    vi.spyOn(React, 'createPortal').mockImplementation((node) => node as unknown as HTMLElement);
    
    describe('BaseNavItem', () => {
      const mockOnSelect = vi.fn();
    
      const baseNavItemConfig: SideNavItem = {
        title: 'Test Item',
        icon: 'testIcon',
        subItems: [],
      };
    
      beforeEach(() => {
        mockOnSelect.mockClear();
      });
    
      it('renders the component with icon and title when not collapsed', () => {
        render(
          <BaseNavItem
            navItemConfig={baseNavItemConfig}
            onSelect={mockOnSelect}
          />
        );
    
        // Check if the icon is rendered
        const icon = screen.getByTestId('test-icon');
        expect(icon).toBeInTheDocument();
    
        // Check if the title is rendered
        const title = screen.getByText('Test Item');
        expect(title).toBeInTheDocument();
      });
    
      it('calls onSelect when the item is clicked', () => {
        render(
          <BaseNavItem
            navItemConfig={baseNavItemConfig}
            onSelect={mockOnSelect}
          />
        );
    
        const button = screen.getByRole('button');
        userEvent.click(button);
    
        expect(mockOnSelect).toHaveBeenCalledTimes(1);
        expect(mockOnSelect).toHaveBeenCalledWith(baseNavItemConfig);
      });
    
      it('renders as a div when asDiv prop is true', () => {
        render(
          <BaseNavItem
            navItemConfig={baseNavItemConfig}
            onSelect={mockOnSelect}
            asDiv
          />
        );
    
        const divElement = screen.getByText('Test Item').closest('div');
        expect(divElement).toBeInTheDocument();
        expect(divElement).not.toHaveAttribute('role', 'button');
      });
    
      it('renders in collapsed state with tooltip', () => {
        // Override the mock for isCollapsed
        vi.mocked(require('@/features/navigation/sidenav/hook/useSideNavigationStore').useSideNavigationStore).mockReturnValue({
          isCollapsed: true,
        });
    
        render(
          <BaseNavItem
            navItemConfig={baseNavItemConfig}
            onSelect={mockOnSelect}
          />
        );
    
        // Icon should be present
        const icon = screen.getByTestId('test-icon');
        expect(icon).toBeInTheDocument();
    
        // Title should not be visible directly
        const title = screen.queryByText('Test Item');
        expect(title).not.toBeInTheDocument();
    
        // Tooltip should be rendered
        const tooltip = screen.getByText('Test Item');
        expect(tooltip).toBeInTheDocument();
      });
    
      it('shows ChevronRightIcon when subItems are present', () => {
        const navItemWithSubItems: SideNavItem = {
          ...baseNavItemConfig,
          subItems: [{ title: 'Sub Item', icon: 'testIcon', subItems: [] }],
        };
    
        render(
          <BaseNavItem
            navItemConfig={navItemWithSubItems}
            onSelect={mockOnSelect}
          />
        );
    
        const chevronIcon = screen.getByTestId('chevron-right-icon'); // Assuming ChevronRightIcon has data-testid
        expect(chevronIcon).toBeInTheDocument();
      });
    
      it('does not show ChevronRightIcon when subItems are empty', () => {
        render(
          <BaseNavItem
            navItemConfig={baseNavItemConfig}
            onSelect={mockOnSelect}
          />
        );
    
        const chevronIcon = screen.queryByTestId('chevron-right-icon');
        expect(chevronIcon).not.toBeInTheDocument();
      });
    
      it('applies the correct variant based on active state', () => {
        // Override the mock for useIsNavItemActive
        vi.mocked(require('@/features/navigation/sidenav/hook/useIsNavItemActive').useIsNavItemActive).mockReturnValue(true);
    
        render(
          <BaseNavItem
            navItemConfig={baseNavItemConfig}
            onSelect={mockOnSelect}
          />
        );
    
        const element = screen.getByText('Test Item').closest('button');
        expect(element).toHaveClass('nav-item-class');
      });
    });
    

    Explanation of the Test Cases

    1. Rendering the Component (Not Collapsed):

      • Test: Ensures that when isCollapsed is false, the component renders both the icon and the title.
      • Approach: Render the component and check for the presence of the icon and title in the DOM.
    2. onSelect Callback Invocation:

      • Test: Verifies that clicking the component triggers the onSelect callback with the correct navItemConfig.
      • Approach: Simulate a user click on the button and assert that the mock function is called appropriately.
    3. Rendering as a div:

      • Test: Checks that when the asDiv prop is true, the component renders as a div instead of a button.
      • Approach: Pass the asDiv prop and verify the rendered element's tag.
    4. Rendering in Collapsed State with Tooltip:

      • Test: Ensures that in a collapsed state, the title is not directly visible and a tooltip appears instead.
      • Approach: Mock the isCollapsed state as true, render the component, and check for the presence of the tooltip.
    5. Displaying ChevronRightIcon When Sub-Items Are Present:

      • Test: Verifies that the ChevronRightIcon is displayed when the navItemConfig has subItems.
      • Approach: Provide a navItemConfig with subItems and check for the presence of the chevron icon.
    6. Not Displaying ChevronRightIcon When Sub-Items Are Absent:

      • Test: Ensures that the chevron icon is not rendered when there are no subItems.
      • Approach: Provide a navItemConfig without subItems and assert the absence of the chevron icon.
    7. Applying Correct Variant Based on Active State:

      • Test: Checks that the component applies the correct CSS classes based on its active state.
      • Approach: Mock the useIsNavItemActive hook to return true and verify the applied class names.

    Additional Notes

    • Mocking Dependencies:

      • Many of the component's dependencies (like hooks and utility functions) are mocked to isolate the BaseNavItem component during testing.
      • Ensure that the paths in the vi.mock statements match your project's directory structure.
    • Handling Portals:

      • Since the component uses createPortal for the tooltip, we mock createPortal to render the tooltip content directly in the DOM for easier testing.
    • Testing Icons:

      • The ChevronRightIcon and other icons should ideally have a data-testid attribute to facilitate querying in tests. If not, consider adding them to make testing easier.
    • Component Variants:

      • The NavItemVariants function is mocked to return a consistent class name, simplifying the assertion process.
    • User Events:

      • The @testing-library/user-event library is used to simulate more realistic user interactions compared to fireEvent.

    Running the Tests

    Ensure your vitest configuration is set up correctly. You can run the tests using the following command:

    npx vitest run
    

    Or, if you have a test script in your package.json:

    npm run test
    

    This setup should provide a solid foundation for testing the BaseNavItem component. Depending on your application's specifics, you might need to adjust the mocks or add more test cases to cover additional scenarios.