import { render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { describe, it, expect, vi, beforeEach } from "vitest"; const mocks = vi.hoisted(() => ({ changeAdminUserPassword: vi.fn() })); vi.mock("@/app/lib/services/adminUsers", () => ({ changeAdminUserPassword: mocks.changeAdminUserPassword })); import { ChangePasswordDialog } from "./ChangePasswordDialog"; beforeEach(() => { mocks.changeAdminUserPassword.mockReset(); }); async function fillAndSubmit(password: string, confirm: string) { await userEvent.type(screen.getByLabelText("New password"), password); await userEvent.type(screen.getByLabelText("Confirm password"), confirm); await userEvent.click(screen.getByRole("button", { name: "Change password" })); } describe("ChangePasswordDialog", () => { it("blocks submit when the fields are empty", async () => { render(); await userEvent.click(screen.getByRole("button", { name: "Change password" })); expect(await screen.findByText(/enter and confirm/i)).toBeInTheDocument(); expect(mocks.changeAdminUserPassword).not.toHaveBeenCalled(); }); it("blocks submit when the password is too short", async () => { render(); await fillAndSubmit("abc", "abc"); expect(await screen.findByText(/at least 6 characters/i)).toBeInTheDocument(); expect(mocks.changeAdminUserPassword).not.toHaveBeenCalled(); }); it("blocks submit when the passwords do not match", async () => { render(); await fillAndSubmit("Passw0rd!", "Different1!"); expect(await screen.findByText(/do not match/i)).toBeInTheDocument(); expect(mocks.changeAdminUserPassword).not.toHaveBeenCalled(); }); it("submits a matching password", async () => { mocks.changeAdminUserPassword.mockResolvedValue({ updated: 1 }); render(); await fillAndSubmit("Passw0rd!", "Passw0rd!"); await waitFor(() => expect(mocks.changeAdminUserPassword).toHaveBeenCalledWith(9, "Passw0rd!")); expect(await screen.findByText(/changed successfully/i)).toBeInTheDocument(); }); it("shows an error when the request fails", async () => { mocks.changeAdminUserPassword.mockRejectedValue(new Error("Server error")); render(); await fillAndSubmit("Passw0rd!", "Passw0rd!"); expect(await screen.findByText("Server error")).toBeInTheDocument(); }); it("disables submit while the request is pending", async () => { let resolve!: (v: { updated: number }) => void; mocks.changeAdminUserPassword.mockReturnValue( new Promise((r) => { resolve = r; }), ); render(); await userEvent.type(screen.getByLabelText("New password"), "Passw0rd!"); await userEvent.type(screen.getByLabelText("Confirm password"), "Passw0rd!"); await userEvent.click(screen.getByRole("button", { name: "Change password" })); await waitFor(() => expect(screen.getByRole("button", { name: "Change password" })).toBeDisabled()); resolve({ updated: 1 }); }); });