How to simulate text selection in testCafe
Asked Answered
M

1

5

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?

Mccutchen answered 2/10, 2018 at 19:14 Comment(0)
C
9

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();
});
Contrasty answered 3/10, 2018 at 11:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.