| 1 |
import React from "react"; |
| 2 |
import { cleanup, fireEvent, render, screen } from "@testing-library/react"; |
| 3 |
import { afterEach, describe, expect, it, vi } from "vitest"; |
| 4 |
// Component |
| 5 |
import PasswordInput, { PropsToPasswordInput } from "./PasswordInput"; |
| 6 |
|
| 7 |
const mockOnChange = vi.fn(); |
| 8 |
const mockOnRevealHandler = vi.fn(); |
| 9 |
|
| 10 |
const initialProps: PropsToPasswordInput = { |
| 11 |
dataCy: "password-input", |
| 12 |
name: "Password", |
| 13 |
onChange: mockOnChange, |
| 14 |
onRevealHandler: mockOnRevealHandler, |
| 15 |
value: "Secret123", |
| 16 |
}; |
| 17 |
|
| 18 |
describe("PasswordInput Component", () => { |
| 19 |
afterEach(() => { |
| 20 |
vi.clearAllMocks(); |
| 21 |
cleanup(); |
| 22 |
}); |
| 23 |
|
| 24 |
it("renders the PasswordInput component", async () => { |
| 25 |
render(<PasswordInput {...initialProps} />); |
| 26 |
|
| 27 |
const password = screen.getByLabelText("Password"); |
| 28 |
expect(password).toHaveValue("Secret123"); |
| 29 |
expect(password).toHaveAttribute("type", "text"); |
| 30 |
}); |
| 31 |
|
| 32 |
it("renders the PasswordInput component unobscured", async () => { |
| 33 |
const props: PropsToPasswordInput = { |
| 34 |
...initialProps, |
| 35 |
passwordHidden: true, |
| 36 |
}; |
| 37 |
|
| 38 |
render(<PasswordInput {...props} />); |
| 39 |
|
| 40 |
const password = screen.getByLabelText("Password"); |
| 41 |
expect(password).toHaveValue("Secret123"); |
| 42 |
expect(password).toHaveAttribute("type", "password"); |
| 43 |
}); |
| 44 |
|
| 45 |
it("allows changing PasswordInput component", async () => { |
| 46 |
const props: PropsToPasswordInput = { |
| 47 |
...initialProps, |
| 48 |
value: "", |
| 49 |
}; |
| 50 |
|
| 51 |
const PASSWORD = "Secret123"; |
| 52 |
|
| 53 |
render(<PasswordInput {...props} />); |
| 54 |
|
| 55 |
const password = screen.getByLabelText("Password"); |
| 56 |
expect(password).toHaveValue(""); |
| 57 |
expect(password).toHaveAttribute("type", "text"); |
| 58 |
|
| 59 |
fireEvent.change(password, { target: { value: PASSWORD } }); |
| 60 |
expect(mockOnChange).toHaveBeenCalledExactlyOnceWith(PASSWORD); |
| 61 |
}); |
| 62 |
|
| 63 |
it("allows to preview the PasswordInput component", async () => { |
| 64 |
render(<PasswordInput {...initialProps} />); |
| 65 |
|
| 66 |
const password = screen.getByLabelText("Password"); |
| 67 |
expect(password).toHaveValue("Secret123"); |
| 68 |
expect(password).toHaveAttribute("type", "text"); |
| 69 |
|
| 70 |
// Show |
| 71 |
const hideButton = screen.getByLabelText("Hide password"); |
| 72 |
fireEvent.click(hideButton); |
| 73 |
|
| 74 |
expect(mockOnRevealHandler).toHaveBeenCalledExactlyOnceWith(true); |
| 75 |
}); |
| 76 |
}); |