Context
I am trying to Unit test my components to achieve 100% coverage but with the following MenuItem component one of the branch is not being covered. To provide more clarity, here is the parent component from which it is being rendered.
Menu.tsx
"use client";
import menu from "@/data/menu.json";
import { usePathname } from "next/navigation";
import React, { useState } from "react";
import styles from "./styles.module.css";
import MenuItem from "../MenuItem";
import { RxHamburgerMenu } from "react-icons/rx";
import MenuModal from "@/modals/MenuModal";
const Menu: React.FC = () => {
const pathname = usePathname();
const [isMenuModalVisible, setMenuModalVisibliity] = useState(false);
const toggleMenuModal = () =>
setMenuModalVisibliity((prevState) => !prevState);
return (
<nav>
<RxHamburgerMenu
onClick={toggleMenuModal}
size={24}
className={styles.hamburgerMenu}
data-testid={"hamburger-menu-icon"}
/>
<ul className={styles.wrapper}>
{menu.map((item) => {
return <MenuItem key={item.id} {...item} pathname={pathname} />;
})}
</ul>
{isMenuModalVisible && <MenuModal onClose={toggleMenuModal} />}
</nav>
);
};
export default Menu;
MenuItem.tsx
import Link from "next/link";
import { memo } from "react";
import styles from "./styles.module.css";
interface MenuItemProps {
id: string;
label: string;
href: string;
pathname: string;
}
const MenuItem: React.FC<MenuItemProps> = ({ href, label, pathname }) => {
return (
<li>
<Link
href={href}
data-testid="menu-item"
className={pathname === href ? styles.selected : undefined}
>
{label}
</Link>
</li>
);
};
export default memo(MenuItem);
MenuItem.test.tsx
The tests I have written are as follows:
import MenuItem from "@/components/MenuItem";
import { render, screen } from "@testing-library/react";
import { usePathname } from "next/navigation";
describe("MenuItem", () => {
it("should render successfully", async () => {
const { container } = render(
<MenuItem href="/" id="home" label="Home" pathname="/" />
);
const menuItem = await screen.findByTestId("menu-item");
expect(menuItem).toHaveClass("selected");
expect(container).toMatchSnapshot();
});
it("should render successfully without the selected class", async () => {
const { container } = render(
<MenuItem href="/about-us" id="home" label="Home" pathname="/" />
);
const menuItem = await screen.findByTestId("menu-item");
expect(menuItem).not.toHaveClass("selected");
expect(container).toMatchSnapshot();
});
});
Branch not being covered
href ? styles.selected
Screenshots
I tried mocking the next/navigation
library and usePathname
hook but it kept failing to cover the branch.