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).to.deep.equal({
17 element: $el.get(0),
18 method: 'focus',
19 });
20 });
21
22 // unfocus the button
23 cy.realPress('Tab');
24 cy.focused().should('not.exist');
25
26 // restore the snapshotted selection
27 cy.get('@button').then(() => {
28 restoreSelection(selection);
29 });
30
31 cy.focused().should('exist');
32 cy.get('@button').should('have.focus');
33});
34
35it('should restore input selections', () => {
36 let selection: RestoreSelection | null = null;
37
38 mount(<input type="text" name="text" />);
39
40 // type and move selection
41 cy.get('input').as('input').focus();
42 cy.realType('test');
43 cy.realPress('ArrowLeft');
44 cy.realPress('ArrowLeft');
45
46 // snapshot the selection
47 cy.get('@input').then($el => {
48 selection = snapshotSelection();
49
50 // check selection matches expected state
51 expect(selection).to.deep.equal({
52 element: $el.get(0),
53 method: 'setSelectionRange',
54 arguments: [2, 2, 'none'],
55 });
56 });
57
58 // unfocus the input
59 cy.realPress('Tab');
60 cy.focused().should('not.exist');
61
62 // restore the snapshotted selection
63 cy.get('@input').then(() => {
64 restoreSelection(selection);
65 });
66
67 // modify input at selected caret and check value
68 cy.focused().should('exist');
69 cy.realType('test');
70 cy.get('@input').should('have.value', 'tetestst');
71});
72
73it('should restore selections otherwise', async () => {
74 let selection: RestoreSelection | null = null;
75
76 // type and move selection
77 cy.get('#editable').as('editable').focus();
78 cy.realType('test');
79 cy.realPress('ArrowLeft');
80 cy.realPress('ArrowLeft');
81
82 // snapshot the selection
83 cy.get('@editable').then($el => {
84 selection = snapshotSelection();
85
86 // check selection matches expected state
87 expect(selection).to.have.property('element', $el.get(0));
88 expect(selection).to.have.property('method', 'range');
89 expect(selection).to.have.property('range');
90 });
91
92 // unfocus the input
93 cy.realPress('Tab');
94 cy.focused().should('not.exist');
95
96 // restore the snapshotted selection
97 cy.get('@editable').then(() => {
98 restoreSelection(selection);
99 });
100
101 // modify input at selected caret and check value
102 cy.focused().should('exist');
103 cy.realType('test');
104 cy.get('@editable').should('have.text', 'tetestst');
105});