-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathOtpInput.test.tsx
More file actions
88 lines (59 loc) · 2.3 KB
/
OtpInput.test.tsx
File metadata and controls
88 lines (59 loc) · 2.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/*
* Copyright © 2026 Fells Code, LLC
* Licensed under the GNU Affero General Public License v3.0
* See LICENSE file in the project root for full license information
*/
import { render, screen, fireEvent } from '@testing-library/react';
import OtpInput from '@/components/OtpInput';
describe('OtpInput', () => {
const onChange = jest.fn();
beforeEach(() => {
jest.clearAllMocks();
});
test('renders default number of inputs (6)', () => {
render(<OtpInput value="" onChange={onChange} />);
const inputs = screen.getAllByRole('textbox');
expect(inputs).toHaveLength(6);
});
test('renders custom length', () => {
render(<OtpInput length={4} value="" onChange={onChange} />);
const inputs = screen.getAllByRole('textbox');
expect(inputs).toHaveLength(4);
});
test('calls onChange when typing a number', () => {
render(<OtpInput value="" onChange={onChange} />);
const inputs = screen.getAllByRole('textbox');
fireEvent.change(inputs[0], { target: { value: '1' } });
expect(onChange).toHaveBeenCalledWith('1');
});
test('rejects non-numeric input', () => {
render(<OtpInput value="" onChange={onChange} />);
const inputs = screen.getAllByRole('textbox');
fireEvent.change(inputs[0], { target: { value: 'a' } });
expect(onChange).not.toHaveBeenCalled();
});
test('moves focus to next input after entering digit', () => {
render(<OtpInput value="" onChange={onChange} />);
const inputs = screen.getAllByRole('textbox');
const focusSpy = jest.spyOn(inputs[1], 'focus');
fireEvent.change(inputs[0], { target: { value: '1' } });
expect(focusSpy).toHaveBeenCalled();
});
test('moves focus back on backspace when current empty', () => {
render(<OtpInput value="1" onChange={onChange} />);
const inputs = screen.getAllByRole('textbox');
inputs[1].focus();
fireEvent.keyDown(inputs[1], { key: 'Backspace' });
expect(document.activeElement).toBe(inputs[0]);
});
test('handles paste of full otp', () => {
render(<OtpInput value="" onChange={onChange} />);
const container = screen.getAllByRole('textbox')[0].parentElement!;
fireEvent.paste(container, {
clipboardData: {
getData: () => '123456',
},
});
expect(onChange).toHaveBeenCalledWith('123456');
});
});