skip to Main Content

I want to do some text selection on a text document as shown in the image. The words "automatically translates those" are highlighted using right click and dragging from start to end. I want to perform the similar operation using cypress.
Can someone help me with it?

I have tried trigger mouseover using cypress but that did not seem to work.

2

Answers


  1. You can’t, that’s outside the scope of cypress. You can customize it using the CSS style containing the things you want to highlight.

    Login or Signup to reply.
  2. There is a range object in javascript that can allow you to implement it.

    Roughly speaking, this is how it goes:

    This HTML:

    <div class="section-text">
      <span sid="0" ost="0">S</span> 
      <span sid="0" ost="1">a</span>
      <span sid="0" ost="2">n</span> 
      <span sid="0" ost="3">t</span>
      <span sid="0" ost="4">a</span>
    </div>
    

    using this test

    function selectText($start, $end) {
      const range = document.createRange()
      range.setStart($start[0], 0)
      range.setEnd($end[0], 1)
      cy.window()
        .then(win => win.getSelection().addRange(range))
    }
    
    cy.get('span[ost="0"]').then($start => {
      cy.get('span[ost="4"]').then($end => {
        selectText($start, $end)
      })
    })
    
    cy.window()
      .then(win => win.getSelection().toString())
      .should('eq', 'S a n t a')
    

    Note the text you get back has spaces between the letters, so that may cause you problems in a more complex example that already contains spaces. But you can step through the string and take every second character,

    cy.window()
      .then(win => win.getSelection().toString())
      .then(selection => [...selection].reduce((acc, s, i) => {
        if (i % 2 === 0) acc += s
        return acc
      }, ''))
      .should('eq', 'Santa')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search