1 import { fireEvent, render, screen } from "@testing-library/react"
2 import * as React from "react"
3 import { vi } from "vitest"
4
5 import { OtpInput } from "./otp-input"
6
7 const ControlledOtpInput = ({
8 initialValue = "",
9 onComplete,
10 }: {
11 initialValue?: string
12 onComplete?: (value: string) => void
13 }) => {
14 const [value, setValue] = React.useState(initialValue)
15
16 return (
17 <OtpInput
18 aria-label="Verification code"
19 value={value}
20 onChange={setValue}
21 onComplete={onComplete}
22 />
23 )
24 }
25
26 describe("OtpInput", () => {
27 it("renders six inputs by default", () => {
28 render(<ControlledOtpInput />)
29
30 expect(screen.getByRole("group")).toBeInTheDocument()
31 expect(screen.getAllByRole("textbox")).toHaveLength(6)
32 })
33
34 it("accepts only numeric values", () => {
35 render(<ControlledOtpInput />)
36
37 const [firstInput] = screen.getAllByRole("textbox")
38
39 fireEvent.change(firstInput, { target: { value: "a1b" } })
40
41 expect(firstInput).toHaveValue("1")
42 })
43
44 it("fills the inputs when pasting a complete code", () => {
45 const onComplete = vi.fn()
46
47 render(<ControlledOtpInput onComplete={onComplete} />)
48
49 const inputs = screen.getAllByRole("textbox")
50
51 fireEvent.paste(inputs[0], {
52 clipboardData: {
53 getData: () => "12a3456",
54 },
55 })
56
57 expect(inputs.map((input) => (input as HTMLInputElement).value)).toEqual([
58 "1",
59 "2",
60 "3",
61 "4",
62 "5",
63 "6",
64 ])
65 expect(onComplete).toHaveBeenCalledWith("123456")
66 })
67
68 it("clears the previous input when backspacing from an empty input", () => {
69 render(<ControlledOtpInput initialValue="1" />)
70
71 const inputs = screen.getAllByRole("textbox")
72
73 fireEvent.keyDown(inputs[1], { key: "Backspace" })
74
75 expect(inputs[0]).toHaveValue("")
76 })
77 })