|
| 1 | +import { fireEvent, render } from '@testing-library/react'; |
| 2 | +import InputNumber, { InputNumberRef } from 'rc-input-number'; |
| 3 | +import { spyElementPrototypes } from 'rc-util/lib/test/domHook'; |
| 4 | +import React from 'react'; |
| 5 | + |
| 6 | +const getInputRef = () => { |
| 7 | + const ref = React.createRef<InputNumberRef>(); |
| 8 | + render(<InputNumber ref={ref} defaultValue={12345} />); |
| 9 | + return ref; |
| 10 | +}; |
| 11 | + |
| 12 | +describe('InputNumber.Focus', () => { |
| 13 | + let inputSpy: ReturnType<typeof spyElementPrototypes>; |
| 14 | + let focus: ReturnType<typeof jest.fn>; |
| 15 | + let setSelectionRange: ReturnType<typeof jest.fn>; |
| 16 | + |
| 17 | + beforeEach(() => { |
| 18 | + focus = jest.fn(); |
| 19 | + setSelectionRange = jest.fn(); |
| 20 | + inputSpy = spyElementPrototypes(HTMLInputElement, { |
| 21 | + focus, |
| 22 | + setSelectionRange, |
| 23 | + }); |
| 24 | + }); |
| 25 | + |
| 26 | + afterEach(() => { |
| 27 | + inputSpy.mockRestore(); |
| 28 | + }); |
| 29 | + |
| 30 | + it('start', () => { |
| 31 | + const input = getInputRef(); |
| 32 | + input.current?.focus({ cursor: 'start' }); |
| 33 | + |
| 34 | + expect(focus).toHaveBeenCalled(); |
| 35 | + expect(setSelectionRange).toHaveBeenCalledWith(expect.anything(), 0, 0); |
| 36 | + }); |
| 37 | + |
| 38 | + it('end', () => { |
| 39 | + const input = getInputRef(); |
| 40 | + input.current?.focus({ cursor: 'end' }); |
| 41 | + |
| 42 | + expect(focus).toHaveBeenCalled(); |
| 43 | + expect(setSelectionRange).toHaveBeenCalledWith(expect.anything(), 5, 5); |
| 44 | + }); |
| 45 | + |
| 46 | + it('all', () => { |
| 47 | + const input = getInputRef(); |
| 48 | + input.current?.focus({ cursor: 'all' }); |
| 49 | + |
| 50 | + expect(focus).toHaveBeenCalled(); |
| 51 | + expect(setSelectionRange).toHaveBeenCalledWith(expect.anything(), 0, 5); |
| 52 | + }); |
| 53 | + |
| 54 | + it('disabled should reset focus', () => { |
| 55 | + const { container, rerender } = render(<InputNumber prefixCls="rc-input-number" />); |
| 56 | + const input = container.querySelector('input')!; |
| 57 | + |
| 58 | + fireEvent.focus(input); |
| 59 | + expect(container.querySelector('.rc-input-number-focused')).toBeTruthy(); |
| 60 | + |
| 61 | + rerender(<InputNumber prefixCls="rc-input-number" disabled />); |
| 62 | + fireEvent.blur(input); |
| 63 | + |
| 64 | + expect(container.querySelector('.rc-input-number-focused')).toBeFalsy(); |
| 65 | + }); |
| 66 | +}); |
0 commit comments