6

Can someone please, assist in following: Short explanation: opened one page, taken text element, then opened second page nd among 4 or 5 elements, need to assert that element from page one, is inside created array of those several elements. Wrote this code:

Cypress.Commands.add(
'assertForOpenedElementVisible',
 (list1, list2, notDisplayedElementMsg) => {
const textsArray = []
cy.get('body').then((body) => {
  if (body.find(list1).length > 0) {
    cy.get(list1).each(($el, index) => {
      const text1 = $el.text().replace(', ', '')

      cy.get(list1).eq(index).click()
      cy.wait(1000)

      cy.get(list2)
        .each(($el, index) => {
          const text = $el.text().replace(', ', '')
          textsArray.push(text)
          cy.log(textsArray)
          cy.log(text)
        })
        .then(() => {
          cy.wrap(expect(textsArray).to.include(text1))
        })
    })
  } else {
    cy.log(notDisplayedElementMsg)
  }
 })
 }
)

And when check Test runner - I got elements, but test fails:

enter image description here

How to correctly assert that? Thank you in advance

1 Answer 1

7

You can do an assertion like:

expect(text1).to.be.oneOf(textsArray)

OR, you can directly assert without using each() as well like:

cy.get(list2).should(($list2) => {
  expect($list2.eq(3)).to.contain('49') //If you know the position
})

cy.get(list2)
  .invoke('text')
  .then((text) => {
    expect(text).to.contain('49') //If you don't know the position
  })
Sign up to request clarification or add additional context in comments.

7 Comments

Tried, but it fails again with error: AssertionError expected '49' to be one of [ Array(4) ]
change const textsArray = [] to var textsArray = [].
@aAlapan Das - unfortunatelly, same error with 'var' instead 'const'
I don't know why textsArray.push(text) is not working and also in the first itration why the array size is 4 as per logs? Can you post your html for list2, so that I can debug some more? Also you don't have to use cy.wrap you can directly write the expect statement
Array is size 4 because there are 4 elements shown on page and one of them is just the one I need to assert. Unfortunately, can not provide you html, sorry for that. With or without cy.wrap, only changes error thrown, but it does not work either way
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.