import { render, screen, fireEvent, act, waitFor } from "@testing-library/react";
import { describe, it, expect, vi, afterEach } from "vitest";
vi.mock("@/app/lib/ThemeContext", () => ({
useTheme: () => ({ isDark: false, toggle: vi.fn() }),
}));
// Skip exit animations so unmount timing reflects the auto-dismiss timer only.
vi.mock("framer-motion", () => ({
AnimatePresence: ({ children }: { children: React.ReactNode }) => <>{children}>,
motion: {
div: ({
children,
role,
onClick,
className,
initial,
animate,
exit,
}: {
children: React.ReactNode;
role?: string;
onClick?: () => void;
className?: string;
initial?: { x?: string };
animate?: { x?: string };
exit?: { x?: string };
}) => (
{children}
),
},
}));
import { ToastProvider, useToast } from "./ToastContext";
const MSG = "Profile updated";
// Minimal consumer that fires a toast when its button is clicked.
function Trigger({ message = MSG }: { message?: string }) {
const { showToast } = useToast();
return ;
}
afterEach(() => {
vi.useRealTimers();
});
describe("ToastContext", () => {
it("renders the message when showToast is called", () => {
render(
,
);
expect(screen.queryByText(MSG)).toBeNull();
fireEvent.click(screen.getByText("fire"));
expect(screen.getByText(MSG)).toBeInTheDocument();
});
it("stays visible for 3.5s and is gone by 4s", async () => {
vi.useFakeTimers({ shouldAdvanceTime: true });
render(
,
);
fireEvent.click(screen.getByText("fire"));
expect(screen.getByText(MSG)).toBeInTheDocument();
await act(async () => {
await vi.advanceTimersByTimeAsync(3500);
});
expect(screen.getByText(MSG)).toBeInTheDocument();
await act(async () => {
await vi.advanceTimersByTimeAsync(500);
});
await waitFor(() => expect(screen.queryByText(MSG)).toBeNull());
});
it("dismisses the toast when it is clicked", async () => {
render(
,
);
fireEvent.click(screen.getByText("fire"));
const toast = screen.getByText(MSG);
fireEvent.click(toast);
await waitFor(() => expect(screen.queryByText(MSG)).toBeNull());
});
it("centres the toast via framer-motion transform, not the -translate-x-1/2 class", async () => {
render(
,
);
fireEvent.click(screen.getByText("fire"));
const toast = screen.getByRole("status");
// framer-motion is mocked, so assert the x offsets it is given (it emits translateX(-50%)).
expect(toast).toHaveAttribute("data-initial-x", "-50%");
expect(toast).toHaveAttribute("data-animate-x", "-50%");
expect(toast).toHaveAttribute("data-exit-x", "-50%");
expect(toast).not.toHaveClass("-translate-x-1/2");
});
it("is a no-op (does not throw) when useToast is used outside a provider", () => {
render();
expect(() => fireEvent.click(screen.getByText("fire"))).not.toThrow();
expect(screen.queryByText(MSG)).toBeNull();
});
});