|
| 1 | +import {getSelectionRange, setSelectionRange} from 'utils' |
| 2 | +import {setup} from '__tests__/helpers/utils' |
| 3 | + |
| 4 | +test('range on input', () => { |
| 5 | + const {element} = setup('<input value="foo"/>') |
| 6 | + |
| 7 | + expect(getSelectionRange(element as HTMLInputElement)).toEqual({ |
| 8 | + selectionStart: 0, |
| 9 | + selectionEnd: 0, |
| 10 | + }) |
| 11 | + |
| 12 | + setSelectionRange(element as HTMLInputElement, 0, 0) |
| 13 | + |
| 14 | + expect(element).toHaveProperty('selectionStart', 0) |
| 15 | + expect(element).toHaveProperty('selectionEnd', 0) |
| 16 | + expect(getSelectionRange(element as HTMLInputElement)).toEqual({ |
| 17 | + selectionStart: 0, |
| 18 | + selectionEnd: 0, |
| 19 | + }) |
| 20 | + |
| 21 | + setSelectionRange(element as HTMLInputElement, 2, 3) |
| 22 | + |
| 23 | + expect(element).toHaveProperty('selectionStart', 2) |
| 24 | + expect(element).toHaveProperty('selectionEnd', 3) |
| 25 | + expect(getSelectionRange(element as HTMLInputElement)).toEqual({ |
| 26 | + selectionStart: 2, |
| 27 | + selectionEnd: 3, |
| 28 | + }) |
| 29 | +}) |
| 30 | + |
| 31 | +test('range on contenteditable', () => { |
| 32 | + const {element} = setup('<div contenteditable="true">foo</div>') |
| 33 | + |
| 34 | + expect(getSelectionRange(element as HTMLInputElement)).toEqual({ |
| 35 | + selectionStart: null, |
| 36 | + selectionEnd: null, |
| 37 | + }) |
| 38 | + |
| 39 | + setSelectionRange(element as HTMLDivElement, 0, 0) |
| 40 | + |
| 41 | + expect(getSelectionRange(element as HTMLInputElement)).toEqual({ |
| 42 | + selectionStart: 0, |
| 43 | + selectionEnd: 0, |
| 44 | + }) |
| 45 | + |
| 46 | + setSelectionRange(element as HTMLDivElement, 2, 3) |
| 47 | + |
| 48 | + expect(document.getSelection()?.anchorNode).toBe(element?.firstChild) |
| 49 | + expect(document.getSelection()?.focusNode).toBe(element?.firstChild) |
| 50 | + expect(document.getSelection()?.anchorOffset).toBe(2) |
| 51 | + expect(document.getSelection()?.focusOffset).toBe(3) |
| 52 | + expect(getSelectionRange(element as HTMLInputElement)).toEqual({ |
| 53 | + selectionStart: 2, |
| 54 | + selectionEnd: 3, |
| 55 | + }) |
| 56 | +}) |
| 57 | + |
| 58 | +test('range on input without selection support', () => { |
| 59 | + const {element} = setup(`<input type="number" value="123"/>`) |
| 60 | + |
| 61 | + expect(getSelectionRange(element as HTMLInputElement)).toEqual({ |
| 62 | + selectionStart: null, |
| 63 | + selectionEnd: null, |
| 64 | + }) |
| 65 | + |
| 66 | + setSelectionRange(element as HTMLInputElement, 1, 2) |
| 67 | + |
| 68 | + expect(getSelectionRange(element as HTMLInputElement)).toEqual({ |
| 69 | + selectionStart: 1, |
| 70 | + selectionEnd: 2, |
| 71 | + }) |
| 72 | +}) |
0 commit comments