import { render, screen, fireEvent, waitFor } from "@testing-library/react"; import { describe, it, expect, vi } from "vitest"; import { AddLocationDialog } from "./AddLocationDialog"; describe("AddLocationDialog", () => { it("is closed until triggered", () => { render(); expect(screen.queryByRole("dialog")).not.toBeInTheDocument(); }); it("opens on trigger and asks for confirmation naming the parent", () => { render(); fireEvent.click(screen.getByRole("button", { name: "Add child location" })); expect(screen.getByRole("dialog")).toBeInTheDocument(); // Title and body copy both name the parent; assert via the dialog heading to stay unambiguous. expect(screen.getByRole("heading", { name: /under Malaysia/ })).toBeInTheDocument(); }); it("requires code, name and type before confirming", async () => { const onConfirm = vi.fn(); render(); fireEvent.click(screen.getByRole("button", { name: "Add child location" })); fireEvent.click(screen.getByRole("button", { name: "Confirm" })); expect(await screen.findByText("Code, name and type are required.")).toBeInTheDocument(); expect(onConfirm).not.toHaveBeenCalled(); }); it("calls onConfirm with the entered fields and closes on success", async () => { const onConfirm = vi.fn().mockResolvedValue(undefined); render(); fireEvent.click(screen.getByRole("button", { name: "Add child location" })); fireEvent.change(screen.getByLabelText("Code"), { target: { value: "WM" } }); fireEvent.change(screen.getByLabelText("Name"), { target: { value: "West Malaysia" } }); fireEvent.click(screen.getByRole("combobox", { name: "Type" })); fireEvent.click(await screen.findByRole("option", { name: "Region" })); fireEvent.click(screen.getByRole("button", { name: "Confirm" })); await waitFor(() => expect(onConfirm).toHaveBeenCalledWith({ code: "WM", name: "West Malaysia", type: "R" }), ); await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); }); it("offers child types as options (no free text, no Global root)", async () => { render(); fireEvent.click(screen.getByRole("button", { name: "Add child location" })); fireEvent.click(screen.getByRole("combobox", { name: "Type" })); expect(await screen.findByRole("option", { name: "Branch" })).toBeInTheDocument(); expect(screen.queryByRole("option", { name: "Global" })).not.toBeInTheDocument(); }); it("Cancel closes the dialog without submitting", async () => { const onConfirm = vi.fn(); render(); fireEvent.click(screen.getByRole("button", { name: "Add child location" })); fireEvent.click(screen.getByRole("button", { name: "Cancel" })); await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument()); expect(onConfirm).not.toHaveBeenCalled(); }); });