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(() => ({ apiGet: vi.fn(), changeOwnPassword: vi.fn() })); vi.mock("@/app/lib/clientApi", async (importOriginal) => ({ ApiError: (await importOriginal()).ApiError, apiGet: mocks.apiGet, })); vi.mock("@/app/lib/services/adminUsers", () => ({ changeOwnPassword: mocks.changeOwnPassword })); import { PasswordRulesHint } from "./PasswordRulesHint"; import ChangePasswordDialog from "@/app/components/app/ChangePasswordDialog"; import { ApiError } from "@/app/lib/clientApi"; const RULES = [ { param: "INPUT_LENGTH_MIN", value: 8 }, { param: "UPPERCASE_LENGTH_MIN", value: 1 }, { param: "SPACE_NOT_ALLOWED", value: null }, ]; beforeEach(() => { mocks.apiGet.mockReset().mockResolvedValue(RULES); mocks.changeOwnPassword.mockReset(); }); describe("PasswordRulesHint", () => { it("lists only the switched-on rules, with their numbers", async () => { render(); expect(await screen.findByText("Length: at least 8")).toBeInTheDocument(); expect(screen.getByText("Capital letters: at least 1")).toBeInTheDocument(); expect(screen.getByText("No spaces")).toBeInTheDocument(); expect(screen.getAllByRole("listitem")).toHaveLength(3); expect(screen.queryByText(/symbol/i)).toBeNull(); expect(mocks.apiGet).toHaveBeenCalledWith("/api/password-rules"); }); it("reads the public route on the signed-out page", async () => { render(); await screen.findByText("No spaces"); expect(mocks.apiGet).toHaveBeenCalledWith("/api/public/password-rules"); }); it("shows nothing when the rules fail to load", async () => { mocks.apiGet.mockRejectedValue(new Error("down")); const { container } = render(); await waitFor(() => expect(mocks.apiGet).toHaveBeenCalled()); expect(container).toBeEmptyDOMElement(); }); }); describe("PASSWORD_RULE refusal", () => { it("names the broken rule at the password field of the change-password dialog", async () => { mocks.changeOwnPassword.mockRejectedValue( new ApiError("PASSWORD_RULE", 400, { error: "PASSWORD_RULE", code: "PASSWORD_RULE", details: { param: "UPPERCASE_LENGTH_MIN", value: 1 } }), ); render( {}} onDone={() => {}} />); await userEvent.type(screen.getByLabelText("Current password"), "old"); await userEvent.type(screen.getByLabelText("New password"), "abcdefgh"); await userEvent.type(screen.getByLabelText("Confirm password"), "abcdefgh"); await userEvent.click(screen.getByRole("button", { name: "Change password" })); expect(await screen.findByText('Password does not meet the rule "Capital letters: at least 1"')).toBeInTheDocument(); }); });