Mirror: React hooks for accessible, common web interactions. UI super powers without the UI.
1import React from 'react'; 2import { mount } from '@cypress/react'; 3import { RestoreSelection, snapshotSelection, restoreSelection } from '../selection'; 4 5it('should restore focused elements', () => { 6 let selection: RestoreSelection | null = null; 7 8 mount(<button id="button">Focusable</button>); 9 cy.get('button').as('button').focus(); 10 11 // snapshot the selection 12 cy.get('@button').then($el => { 13 selection = snapshotSelection(); 14 15 // check selection matches expected state 16 expect(selection?.element).to.deep.equal( 17 $el.get(0), 18 ); 19 }); 20 21 // unfocus the button 22 cy.realPress('Tab'); 23 cy.focused().should('not.exist'); 24 25 // restore the snapshotted selection 26 cy.get('@button').then(() => { 27 restoreSelection(selection); 28 }); 29 30 cy.focused().should('exist'); 31 cy.get('@button').should('have.focus'); 32}); 33 34it('should restore input selections', () => { 35 let selection: RestoreSelection | null = null; 36 37 mount(<input type="text" name="text" />); 38 39 // type and move selection 40 cy.get('input').as('input').focus(); 41 cy.realType('test'); 42 cy.realPress('ArrowLeft'); 43 cy.realPress('ArrowLeft'); 44 45 // snapshot the selection 46 cy.get('@input').then($el => { 47 selection = snapshotSelection(); 48 49 // check selection matches expected state 50 expect(selection?.element).to.deep.equal( 51 $el.get(0), 52 ); 53 }); 54 55 // unfocus the input 56 cy.realPress('Tab'); 57 cy.focused().should('not.exist'); 58 59 // restore the snapshotted selection 60 cy.get('@input').then(() => { 61 restoreSelection(selection); 62 }); 63 64 // modify input at selected caret and check value 65 cy.focused().should('exist'); 66 cy.realType('test'); 67 cy.get('@input').should('have.value', 'tetestst'); 68}); 69 70it('should restore selections otherwise', async () => { 71 let selection: RestoreSelection | null = null; 72 73 // type and move selection 74 cy.get('#editable').as('editable').focus(); 75 cy.realType('test'); 76 cy.realPress('ArrowLeft'); 77 cy.realPress('ArrowLeft'); 78 79 // snapshot the selection 80 cy.get('@editable').then($el => { 81 selection = snapshotSelection(); 82 83 // check selection matches expected state 84 expect(selection).to.have.property('element', $el.get(0)); 85 expect(selection).to.have.property('method', 'range'); 86 expect(selection).to.have.property('range'); 87 }); 88 89 // unfocus the input 90 cy.realPress('Tab'); 91 cy.focused().should('not.exist'); 92 93 // restore the snapshotted selection 94 cy.get('@editable').then(() => { 95 restoreSelection(selection); 96 }); 97 98 // modify input at selected caret and check value 99 cy.focused().should('exist'); 100 cy.realType('test'); 101 cy.get('@editable').should('have.text', 'tetestst'); 102});