import "@testing-library/jest-dom";
import { fireEvent, render, screen } from "@testing-library/react";
import Alert from "./Alert";
describe("Alert", () => {
test("renders children", () => {
render(Something went wrong.);
expect(screen.getByText("Something went wrong.")).toBeInTheDocument();
});
test("renders the title when provided", () => {
render(Something went wrong.);
expect(screen.getByText("Error")).toBeInTheDocument();
});
test("does not render the title element when title is omitted", () => {
const { container } = render(Content);
expect(container.querySelector(".alert-title")).not.toBeInTheDocument();
});
test("renders rich children (React nodes)", () => {
render(
Bold text and emphasised text
,
);
expect(screen.getByText("Bold text")).toBeInTheDocument();
expect(screen.getByText("emphasised text")).toBeInTheDocument();
});
test("applies the correct variant class", () => {
const { container } = render(Error);
expect(container.firstChild).toHaveClass("alert-error");
});
test("defaults to the info variant", () => {
const { container } = render(Info);
expect(container.firstChild).toHaveClass("alert-info");
});
test("applies an additional className", () => {
const { container } = render(
Content,
);
expect(container.firstChild).toHaveClass("alert", "custom-alert");
});
test("renders the dismiss button when onClose is provided", () => {
render( {}}>Content);
expect(
screen.getByRole("button", { name: /dismiss/i }),
).toBeInTheDocument();
});
test("does not render the dismiss button when onClose is omitted", () => {
render(Content);
expect(
screen.queryByRole("button", { name: /dismiss/i }),
).not.toBeInTheDocument();
});
test("calls onClose when the dismiss button is clicked", () => {
const handleClose = vi.fn();
render(Content);
fireEvent.click(screen.getByRole("button", { name: /dismiss/i }));
expect(handleClose).toHaveBeenCalledTimes(1);
});
test("has role alert for error variant", () => {
render(Error message);
expect(screen.getByRole("alert")).toBeInTheDocument();
});
test("has role alert for warning variant", () => {
render(Warning message);
expect(screen.getByRole("alert")).toBeInTheDocument();
});
test("has role status for info variant", () => {
render(Info message);
expect(screen.getByRole("status")).toBeInTheDocument();
});
test("has role status for success variant", () => {
render(Success message);
expect(screen.getByRole("status")).toBeInTheDocument();
});
});