• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

613
Vistas
Cypress: cómo copiar/pegar una sola palabra de texto de una cadena para pegarla más tarde

Soy nuevo en stackoverflow, así que pido disculpas si esto es un poco por todas partes, pero parece que no puedo encontrar ninguna respuesta fácil en línea para lo que parece una tarea bastante pequeña. :(

Estoy tratando de copiar algunos datos de una ventana emergente que dice algo así como "Felicidades, su referencia (REF1234) se completó con éxito" (solo la parte REF1234) y copiarla para pegarla en otro campo en la siguiente pantalla... Esto es lo que tengo hasta ahora, que espero que tenga sentido para alguien...

 export function addRefToThing() { cy.get('[class="ref-success"]').find(':selected').contains('REF').then(($clipboard) => { const copiedRef = $clipboard[0]._vClipboard.clipboardAction.text; // <<filler steps, moving around pages>> // webpage.RefNo().type(copiedRef)})

Esto es lo más lejos que he podido llegar y sacarme el pelo... Parece que se está quedando atrapado en -find :selected pero no estoy seguro de que esté copiando los datos que quiero...

Soy bastante nuevo en cypress, por lo que esto está resultando bastante confuso y si alguien tiene algún buen material de capacitación con respecto a este tipo de solicitud, ¡sería increíble! ¡Gracias por adelantado!

HTML:

 <div class="notification-group" style="width: 300px; bottom: 0px; right: 0px;"> <span> <div data-id="1" class="notification-wrapper" style="transition: all 300ms ease 0s;"> <div class="notification-template notification success"> <div class="notification-title">Successful</div> <div class="notification-content">Ref (REF123456789) created successfully</div> </div> </div> </span> </div>
almost 3 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Pruébelo con una expresión regular para analizar la referencia.

Usando /\(REF([0-9]+)\)/ obtienes dos coincidencias,

  • coincidencias[0] es el conjunto "(REF123456789)""
  • matches[1] es el grupo interno "123456789"
 cy.get('div.notification-content') .then($el => $el.text().match(/\(REF([0-9]+)\)/)[1]) // parsing step .then(ref => { webpage.RefNo().type(ref) })

En su función,

 export function addRefToRef() { cy.get('[class="ref-success"]').find(':selected').contains('REF') .then(($clipboard) => { const copiedRef = $clipboard[0]._vClipboard.clipboardAction.text; const innerRef = copiedRef.match(/\(REF([0-9]+)\)/)[1]; // <<filler steps, moving around pages>> // webpage.RefNo().type(innerRef) }) }
almost 3 years ago · Juan Pablo Isaza Denunciar

0

Puede guardar directamente el valor de texto interno de la notification-content y usarlo más tarde. No tienes que usar el método del portapapeles.

 //Some code that will trigger the notification cy.get('.notification-content') .should('be.visible') .invoke('text') .then((text) => { cy.log(text) //prints Ref (REF123456789) created successfully })

En caso de que desee guardarlo y luego usarlo más adelante en la prueba, puede usar alias .as :

 //Some code that will trigger the notification cy.get('.notification-content') .should('be.visible') .invoke('text') .as('notificationText') //Some other code cy.get('@notificationText').then((notificationText) => { cy.log(notificationText) //prints Ref (REF123456789) created successfully })

O, si desea afirmar el contenido:

  1. Coincidencia exacta:
 cy.get('.notification-content') .should('be.visible') .and('have.text', 'Ref (REF123456789) created successfully')
  1. Coincidencia parcial
 cy.get('.notification-content') .should('be.visible') .and('include.text', 'REF123456789')

Si solo desea extraer el número de referencia, primero debe usar split para obtener el segundo texto y luego usar slice para eliminar los corchetes de apertura y cierre, algo como esto:

 //Some code that will trigger the notification cy.get('.notification-content').should('be.visible').invoke('text').as('notificationText') //Some other code cy.get('@notificationText').then((notificationText) => { cy.log(notificationText.split(' ')[1].slice(1,-1)) //REF123456789 })
almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda