Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to simulate text selection in testCafe

I have an Ionic/Angular app that reacts to text selections (e.g. for annotation in eBooks). The user can highlight text in the browser, and then a menu pops up (somewhat over-riding / augmenting the browser context menu) to allow actions. I would like to test that feature with testcafe. (The component rendering the text reacts to "selectionchange" events from the browser.)

There appears to be no way to simulate a text selection other than the Select Text command (https://devexpress.github.io/testcafe/documentation/test-api/actions/select-text.html), but this is limited to inputs, textareas, or contenteditables. My text is none of those - it's straight

elements.

Any suggestions on how this might be accomplished?

like image 526
Mark Watkins Avatar asked Jan 28 '23 09:01

Mark Watkins


1 Answers

You are right, the SelectText command is limited to inputs, textareas and contenteditable elements. You can solve the issue with the ClientFunctions mechanism if you implement your own ClientFunction with custom selection logic using the Selection API. I have prepared an example. If you need to select separate parts of text content, modify it as needed.

import { Selector, ClientFunction } from 'testcafe';

fixture `selection`
    .page `http://example.com`;

const selectElement = (selector) => ClientFunction(() => {
    const selection = document.getSelection();
    const range = document.createRange();

    range.selectNode(selector());
    selection.addRange(range);
}, { dependencies: { selector } });

test('selection', async t => {
    await selectElement(Selector('h1'))();

    await t.debug();
});
like image 118
Alex Kamaev Avatar answered Jan 31 '23 22:01

Alex Kamaev