import { render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { PasswordField } from "./PasswordField"; describe("PasswordField", () => { it("should render without errors", () => { const { container } = render(); expect(container).toBeInTheDocument(); }); it("should hide the password by default", () => { render(); expect(screen.getByTestId("password-field")).toHaveAttribute( "type", "password", ); }); it("should show the password on request", async () => { render(); await userEvent.click(screen.getByTestId("show-hide-button")); expect(screen.getByTestId("password-field")).toHaveAttribute( "type", "text", ); }); it("preserves cursor position when toggling visibility", async () => { render(); const input = screen.getByLabelText("Password"); const toggleButton = screen.getByRole("button", { name: /show/i }); // Type text and position cursor await userEvent.type(input, "password123"); input.setSelectionRange(4, 4); // cursor after "pass" // Toggle visibility await userEvent.click(toggleButton); // Verify cursor position preserved await waitFor(() => { expect(input.selectionStart).toBe(4); }); await waitFor(() => { expect(input.selectionEnd).toBe(4); }); }); it("should return focus to input after pressing show/hide", async () => { render(); await userEvent.tab(); expect(screen.getByTestId("password-field")).toHaveFocus(); // Press Show button with keyboard await userEvent.tab(); await userEvent.keyboard("{enter}"); await waitFor(() => { expect(screen.getByTestId("password-field")).toHaveFocus(); }); }); describe("autocomplete", () => { it('defaults autoComplete to "current-password"', () => { render(); expect(screen.getByTestId("password-field")).toHaveAttribute( "autocomplete", "current-password", ); }); it("allows autoComplete to be overridden", () => { render( , ); expect(screen.getByTestId("password-field")).toHaveAttribute( "autocomplete", "new-password", ); }); }); });