Skip to content

Commit fecd638

Browse files
committed
chore: add validator test
1 parent 81e3375 commit fecd638

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

tests/validator.test.tsx

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import KeyCode from 'rc-util/lib/KeyCode';
2+
import InputNumber from '../src';
3+
import { fireEvent, render } from './util/wrapper';
4+
5+
describe('InputNumber.validator', () => {
6+
it('validator on direct input', () => {
7+
const onChange = jest.fn();
8+
const { container } = render(
9+
<InputNumber
10+
defaultValue={0}
11+
validator={(num) => {
12+
return /^[0-9]*$/.test(num);
13+
}}
14+
onChange={onChange}
15+
/>,
16+
);
17+
const input = container.querySelector('input');
18+
fireEvent.focus(input);
19+
20+
fireEvent.change(input, { target: { value: 'a' } });
21+
expect(input.value).toEqual('0');
22+
fireEvent.change(input, { target: { value: '5' } });
23+
expect(input.value).toEqual('5');
24+
expect(onChange).toHaveBeenCalledWith(5);
25+
fireEvent.change(input, { target: { value: '10e' } });
26+
expect(input.value).toEqual('5');
27+
fireEvent.change(input, { target: { value: '_' } });
28+
expect(input.value).toEqual('5');
29+
fireEvent.change(input, { target: { value: '10' } });
30+
expect(input.value).toEqual('10');
31+
expect(onChange).toHaveBeenCalledWith(10);
32+
});
33+
34+
it('validator and formatter', () => {
35+
const onChange = jest.fn();
36+
const { container } = render(
37+
<InputNumber
38+
defaultValue={1}
39+
formatter={(num) => `$ ${num} boeing 737`}
40+
validator={(num) => {
41+
return /^[0-9]*$/.test(num);
42+
}}
43+
onChange={onChange}
44+
/>,
45+
);
46+
const input = container.querySelector('input');
47+
fireEvent.focus(input);
48+
49+
expect(input.value).toEqual('$ 1 boeing 737');
50+
fireEvent.change(input, { target: { value: '5' } });
51+
expect(input.value).toEqual('$ 5 boeing 737');
52+
53+
fireEvent.keyDown(input, {
54+
which: KeyCode.UP,
55+
key: 'ArrowUp',
56+
code: 'ArrowUp',
57+
keyCode: KeyCode.UP,
58+
});
59+
60+
expect(input.value).toEqual('$ 6 boeing 737');
61+
expect(onChange).toHaveBeenLastCalledWith(6);
62+
63+
fireEvent.change(input, { target: { value: '#' } });
64+
expect(input.value).toEqual('$ 6 boeing 737');
65+
66+
fireEvent.keyDown(input, {
67+
which: KeyCode.DOWN,
68+
key: 'ArrowDown',
69+
code: 'ArrowDown',
70+
keyCode: KeyCode.DOWN,
71+
});
72+
73+
expect(input.value).toEqual('$ 5 boeing 737');
74+
expect(onChange).toHaveBeenLastCalledWith(5);
75+
76+
fireEvent.mouseDown(container.querySelector('.rc-input-number-handler-up'), {
77+
which: KeyCode.DOWN,
78+
});
79+
expect(input.value).toEqual('$ 6 boeing 737');
80+
expect(onChange).toHaveBeenLastCalledWith(6);
81+
fireEvent.change(input, { target: { value: 'a' } });
82+
expect(input.value).toEqual('$ 6 boeing 737');
83+
});
84+
});

0 commit comments

Comments
 (0)