CustomLeftSidebar.tsx Component
import { usePathname, useRouter } from 'next/navigation';
interface CustomLeftSidebarProps {
customLeftSidebarData: InnerPathItem;
customLeftSidebarDataIndex: number;
}
export const CustomLeftSidebarItem = (props: CustomLeftSidebarProps) => {
const pathName = usePathname();
const router = useRouter();
return (
<li
className={`hover:bg-[rgb(0,0,0,0.18)] w-[14.625rem] h-[2.813rem] hover:rounded-xl flex items-center p-3 cursor-pointer
${pathName === props.customLeftSidebarData.path && `rounded-xl bg-[rgb(0,0,0,0.18)]`} mb-1 nav_li_item`}
onClick={() => {
router.push(props.customLeftSidebarData.path);
}}
key={`${props.customLeftSidebarData.label}${props.customLeftSidebarDataIndex}`}
data-testid="custom-li-item"
>
{renderIcon(
pathName === props.customLeftSidebarData.path,
props.customLeftSidebarData.label,
)}
<div
className={`p-2 text-sm ${pathName === props.customLeftSidebarData.path && 'font-bold'} text-white`}
>
{props.customLeftSidebarData.label}
</div>
</li>
);
};
CustomLeftSidebar.spec.tsx Testing File
import { fireEvent, render, screen } from '@testing-library/react';
import React from 'react';
import { NextRouter, useRouter } from 'next/router';
import { CustomLeftSideBar } from './CustomLeftSidebar';
import { customLeftSidebarItems } from './CustomLeftSidebarItems';
jest.mock('next/router', () => ({
useRouter: jest.fn(),
NextRouter: jest.fn(),
}));
jest.mock('next/navigation', () => ({
useRouter() {
return {
route: '/Orders',
pathname: '',
query: '',
asPath: '',
push: jest.fn(),
events: {
on: jest.fn(),
off: jest.fn(),
},
beforePopState: jest.fn(() => null),
prefetch: jest.fn(() => null),
};
},
usePathname() {
return '';
},
}));
describe('CustomLeftSideBar', () => {
describe('Click event on Sidebar', () => {
const mockPush = jest.fn();
beforeEach(() => {
const router=useRouter();
console.log(router);
(useRouter as jest.Mock).mockReturnValue({
push: mockPush,
pathname: '/',
} as Partial<NextRouter>);
});
afterEach(() => {
jest.clearAllMocks();
});
it('should navigate to Orders page on click', () => {
const { getByText } = render(
<CustomLeftSideBar customLeftSideBarPathItems={customLeftSidebarItems} />,
);
// Simulate click on the 'Orders' list item
const liElement = getByText('Orders').closest('li')!;
fireEvent.click(liElement);
// Assert that router.push was called with the correct path
expect(mockPush).toHaveBeenCalledWith('/Orders');
});
});
});
I created a custom Left sidebar component containing all the routes. My goal is to locate the "Orders" label in the list and click on it. Although the list item is clicked, I encounter an issue where expect(mockPush).toHaveBeenCalledWith('/Orders'); shows mockPush as undefined. Additionally, when attempting to print the router in beforeEach, it also appears to be undefined.