Cypress assert is a word inside an array

Viewed 137

I need your help. I am trying to assert the existence of a word in an array with cypress. There is an array with the names of music categories, and I should assert the result's title is included in that category. but after running I am getting this cypress error: "assert expected [ Array(1) ] to include Pop Music". I really can not find out what is the problem here. Thank you in advance

    const allMusicTypes = []
    cy.get('.musicCategories')
      .find(selectors.CategoryList + '> a')
      .invoke('text')
      .then((text) => allMusicTypes.push(text.trim()))
      .then(() => {

        cy.get(selectors.results)
          .find('button')
          .click()

        cy.get('.infobox')
          .find('dd')
          .first()
          .invoke('text')
          .then((categoryType) => {
            const resultMusicType = categoryType.split(',')[0]
            expect(allMusicTypes).to.include(resultMusicType.trim())
          })
    
1 Answers

Because .find(selectors.CategoryList + '> a') finds multiple elements, .invoke('text') returns all the text from all elements in one long string.

To get an array from it, get the text of individual elements

const allMusicTypes = []
cy.get('.musicCategories')
  .find(selectors.CategoryList + '> a')
  .each($el => allMusicTypes.push($el.text().trim()))
  .then(() => {
    ...  // test the category type
    expect(allMusicTypes).to.include(resultMusicType.trim())  // array includes
  })

Or treat allMusicTypes as a string rather than an array

cy.get('.musicCategories')
  .find(selectors.CategoryList + '> a')
  .invoke('text')
  .then((text) => text.trim())
  .then((allMusicTypes) => {
    ...  // test the category type
    expect(allMusicTypes).to.include(resultMusicType.trim())  // string includes
  })
Related