import { ChevronRightIcon } from '@heroicons/react/24/solid'; import { isEmpty } from…
- 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
- Assistant
Certainly! Below is an example of how you can create a test file for the
BaseNavItemcomponent 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 theonSelectcallback is triggered correctly, and handling tooltip functionality.Prerequisites
-
Ensure you have the necessary dependencies installed:
npm install --save-dev vitest @testing-library/react @testing-library/jest-dom @testing-library/user-event -
Configure Vitest in your project if you haven't already. Typically, you can add a
vitest.config.tsor configure it in yourpackage.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
-
Rendering the Component (Not Collapsed):
- Test: Ensures that when
isCollapsedisfalse, 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.
- Test: Ensures that when
-
onSelectCallback Invocation:- Test: Verifies that clicking the component triggers the
onSelectcallback with the correctnavItemConfig. - Approach: Simulate a user click on the button and assert that the mock function is called appropriately.
- Test: Verifies that clicking the component triggers the
-
Rendering as a
div:- Test: Checks that when the
asDivprop istrue, the component renders as adivinstead of abutton. - Approach: Pass the
asDivprop and verify the rendered element's tag.
- Test: Checks that when the
-
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
isCollapsedstate astrue, render the component, and check for the presence of the tooltip.
-
Displaying
ChevronRightIconWhen Sub-Items Are Present:- Test: Verifies that the
ChevronRightIconis displayed when thenavItemConfighassubItems. - Approach: Provide a
navItemConfigwithsubItemsand check for the presence of the chevron icon.
- Test: Verifies that the
-
Not Displaying
ChevronRightIconWhen Sub-Items Are Absent:- Test: Ensures that the chevron icon is not rendered when there are no
subItems. - Approach: Provide a
navItemConfigwithoutsubItemsand assert the absence of the chevron icon.
- Test: Ensures that the chevron icon is not rendered when there are no
-
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
useIsNavItemActivehook to returntrueand 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
BaseNavItemcomponent during testing. - Ensure that the paths in the
vi.mockstatements match your project's directory structure.
- Many of the component's dependencies (like hooks and utility functions) are mocked to isolate the
-
Handling Portals:
- Since the component uses
createPortalfor the tooltip, we mockcreatePortalto render the tooltip content directly in the DOM for easier testing.
- Since the component uses
-
Testing Icons:
- The
ChevronRightIconand other icons should ideally have adata-testidattribute to facilitate querying in tests. If not, consider adding them to make testing easier.
- The
-
Component Variants:
- The
NavItemVariantsfunction is mocked to return a consistent class name, simplifying the assertion process.
- The
-
User Events:
- The
@testing-library/user-eventlibrary is used to simulate more realistic user interactions compared tofireEvent.
- The
Running the Tests
Ensure your
vitestconfiguration is set up correctly. You can run the tests using the following command:npx vitest runOr, if you have a test script in your
package.json:npm run testThis setup should provide a solid foundation for testing the
BaseNavItemcomponent. Depending on your application's specifics, you might need to adjust the mocks or add more test cases to cover additional scenarios. -