Search code examples
arrayscypresscypress-cucumber-preprocessor

comparison of two array


I am testing a scenario in Cypress however when I get to compare two arrays at the end of the scenario, the code fails. This is the code where I have a pre-defined array and i want to create the second array. The code fails at the last line saying the second array is an object (I guess somehow I am comparing an array to an object?):

cy.get(desiredCEXs).then( list => { cy.get(expectedCEXnames).should('have.all.members', list)})

I'm very new to Cypress. So, I was wondering how I could fix the code? I thought by using .push() , I am constructing the second array. This is the link to where I am asserting the code https://www.coingecko.com/en/coins/kira-network

Then ('I assert what exchnages KIRA Network is listed on', ()=>
{
    const desiredCEXs = [ 'Gate.io', 'AscendEX (BitMax)', 'Uniswap V2 (Ethereum)', 'Gate.io' ]
    const expectedCEXnames = []
    cy.get('tbody').eq(4).find('tr').as('exchanges')
    cy.get('@exchanges').each( eachExchange =>
    {
        var exTypeText = eachExchange.children('td').eq(2).children('span').children('div').text().trim()
        var exName = eachExchange.children('td').eq(1).children('div').children('a').children('div').text().trim()
        if(exTypeText == 'CEX')
        {
            expectedCEXnames.push(exName)
        }
    })
    .then( () =>
    {
        console.log(expectedCEXnames)
    })
    cy.get(desiredCEXs).then( list => { cy.get(expectedCEXnames).should('have.all.members', list)})
})

Solution

  • The exact way you do it depends if you require ordering check as well as existence check.

    For checking existence each value (any order)

    const desiredCEXs = [ 'Gate.io',...]
    cy.get('tbody').eq(4).find('tr').each(eachExchange => {
      const exName = ...
      if(exTypeText == 'CEX') {
        const isInList = desiredCEXs.includes(exName)
    
        assert(isInList, `${exName} is in the list`)
        // or
        expect(isInList).to.be.ok
        // or
        cy.wrap(exName).should('be.oneOf', desiredCEXs)
      })
    })
    

    For order checking as well as existence, use deep.eq to check both arrays

    const desiredCEXs = [ 'Gate.io',...]
    const actualCEXs = []
    cy.get('tbody').eq(4).find('tr').each(eachExchange => {
      const exName = ...
      if(exTypeText == 'CEX') {
        actualCEXs.push(exName)
      })
    })
    .then(() => {
      cy.wrap(actualCEXs)).should('deep.eq', desiredCEXs)  // note "deep" for array check
    })
    

    Other notes

    • cy.get() is for elements not variables
    • you don't need .as('exchanges')