Tengo el div con el nombre de clase 'okrSelectorSelect__value-container' en DOM.
<div class="okrSelectorSelect__value-container"><div>Este div es opcional . Quiero hacer clic en él y hacer algunas pruebas adicionales con el bloque que aparece después de SI EXISTE . Estoy intentando esto.
cy.get('.okrSelectorSelect__value-container').then(($higherObjectivePick) => { if ($higherObjectivePick.length > 0) { $higherObjectivePick.click(); } });Pero obtuve esto cuando el bloque no está en la página
Aquí está mi solución, pero parece que hay formas mucho más hermosas de hacerlo.
cy.get('body').then($body => { if ($body.find('.okrSelectorSelect__value-container').length > 0) { cy.get('.okrSelectorSelect__value-container').click(); cy.get('.okrSelectorSelect__option').eq(higherOrderObjectiveNumber).click(); } });Puede usar operadores jquery para verificar la existencia de un elemento y envolver esa función como se muestra a continuación, agregando a su archivo support.js:
Cypress.Commands.add("checkIfClassExists", (classToFind) => { return Cypress.$(classToFind).length>0 })Luego en tus pruebas:
if (cy.checkIfClassExists('.okrSelectorSelect__value-container')) { //do something } else { //do nothing }Normalmente hago lo mismo que tú, pero sería más bonito crear un comando personalizado para él como este:
Cypress.Commands.add("clickIfExists",(containerId , ItemId)=>{ cy.get('body').then($body => { if ($body.find(containerId).length > 0) { cy.get(ItemId).click(); } }); }) y de esta manera siempre puede llamarlo así si desea hacer clic en .okrSelectorSelect__option :
cy.clickIfExists(".okrSelectorSelect__value-container",".okrSelectorSelect__option")