|
| 1 | +const { EditorState, ContentState, SelectionState } = require('draft-js'); |
| 2 | +const handleTab = require('../handleTab'); |
| 3 | + |
| 4 | +const toPlainText = (editorState) => editorState.getCurrentContent().getPlainText(); |
| 5 | +const createWithText = (text) => { |
| 6 | + const contentState = ContentState.createFromText(text); |
| 7 | + return EditorState.createWithContent(contentState); |
| 8 | +} |
| 9 | + |
| 10 | +const tabs = (times) => " ".repeat(times || 1); |
| 11 | + |
| 12 | +it('should insert a tab', () => { |
| 13 | + const evt = { preventDefault: jest.fn() }; |
| 14 | + const initialText = ""; |
| 15 | + const before = createWithText(initialText); |
| 16 | + const after = handleTab(evt, before); |
| 17 | + |
| 18 | + expect(toPlainText(before)).toEqual(initialText); |
| 19 | + expect(toPlainText(after)).toEqual(tabs(1)); |
| 20 | +}); |
| 21 | + |
| 22 | +it('should prevent the default event behavior', () => { |
| 23 | + const preventDefault = jest.fn(); |
| 24 | + const evt = { preventDefault }; |
| 25 | + const before = EditorState.createEmpty(); |
| 26 | + |
| 27 | + handleTab(evt, before); |
| 28 | + expect(preventDefault).toHaveBeenCalled(); |
| 29 | +}) |
| 30 | + |
| 31 | +it('should add a tab to an existing tab', () => { |
| 32 | + const evt = { preventDefault: jest.fn() }; |
| 33 | + const initialText = tabs(1); |
| 34 | + const before = createWithText(initialText); |
| 35 | + const after = handleTab(evt, before); |
| 36 | + |
| 37 | + expect(toPlainText(before)).toEqual(initialText); |
| 38 | + expect(toPlainText(after)).toEqual(initialText + tabs(1)); |
| 39 | +}) |
| 40 | + |
| 41 | +it('should replace existing content with the tab', () => { |
| 42 | + const evt = { preventDefault: jest.fn() }; |
| 43 | + const initialText = "hello"; |
| 44 | + |
| 45 | + const currentContent = ContentState.createFromText(initialText); |
| 46 | + const selectInitialtext = SelectionState.createEmpty( |
| 47 | + currentContent.getBlockMap().first().getKey() |
| 48 | + ); |
| 49 | + const before = EditorState.create({ |
| 50 | + allowUndo: true, |
| 51 | + currentContent, |
| 52 | + // Focus the entire initial word |
| 53 | + selection: selectInitialtext.set('focusOffset', initialText.length), |
| 54 | + }); |
| 55 | + |
| 56 | + const after = handleTab(evt, before); |
| 57 | + expect(toPlainText(before)).toEqual(initialText); |
| 58 | + expect(toPlainText(after)).toEqual(tabs(1)); |
| 59 | +}) |
0 commit comments