import React from "react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { ThemeToggle } from "@/app/components/ThemeToggle";
import { useTheme } from "next-themes";
// Mock next-themes
jest.mock("next-themes", () => ({
useTheme: jest.fn(),
}));
describe("ThemeToggle Component", () => {
const setThemeMock = jest.fn();
beforeEach(() => {
jest.clearAllMocks();
(useTheme as jest.Mock).mockReturnValue({
theme: "light",
setTheme: setThemeMock,
});
});
it("renders a placeholder initially (to avoid hydration mismatch)", () => {
const { container } = render();
// Initial render should be the loading div
expect(container.firstChild).toHaveClass("w-9 h-9");
});
it("toggles to dark mode when clicked", async () => {
render();
// Wait for effect to set mounted=true
const button = await screen.findByRole("button", { name: /toggle theme/i });
fireEvent.click(button);
expect(setThemeMock).toHaveBeenCalledWith("dark");
});
it("toggles to light mode when clicked if currently dark", async () => {
(useTheme as jest.Mock).mockReturnValue({
theme: "dark",
setTheme: setThemeMock,
});
render();
const button = await screen.findByRole("button", { name: /toggle theme/i });
fireEvent.click(button);
expect(setThemeMock).toHaveBeenCalledWith("light");
});
});