cypress-cucumber-preprocessor

Cypress & Cucumber: variable in step definition not displayed


I am not able to use a variable declared in a cypress method, within a step definition, outside that Cypress method, within the same step definition.

This is my scenario:

Scenario: Transfer totals verification
        Given I launch the application using the url
        And I click the 'Sign In' button
        And I enter the username 'bbfel@gmail.com'
        And I enter the password '55555'
        And I click the 'Continue' button
        When I navigate to the 'Track Transfers' page
        Then the total amount sent to '<To country>' is '<Total amount sent>'

        Examples:
            | To country     | Total amount sent |
            | United Kingdom | 55555             |

The step definition:

I am trying to use the variables (toCountryCount, eachTransferAmount, amountSentTotal), in the for loop. However, the variable contents are not even displayed in the cy.log() methods that come before the loop.

Then('the total amount sent to {string} is {string}', (toCountry, amountSent) => {

    let toCountryCount
    let eachTransferAmount
    let amountSentTotal

    cy.get('.TrackingTable tr td:nth-of-type(5):visible:contains("' + toCountry + '")').its('length').then(count => {
        toCountryCount = count
        cy.log(toCountryCount) //variable content displayed correctly
    })

    trackTransfersPageObj.sendingTo.contains(toCountry).next('td').then(amount => {
        eachTransferAmount = amount.text().replace('£', '').replace('N', '')
        cy.log(eachTransferAmount) //variable content displayed correctly
    })

    cy.log(toCountryCount) //not working, variable content not displayed
    cy.log(eachTransferAmount) //not working, variable content not displayed

    for (let i = 0; i < toCountryCount; i++) {
        amountSentTotal += parseInt(eachTransferAmount)
    }
})

Solution

  • the problem with your code is that it uses cy-commands together with synchronous statements. Cy-commands get queued and run at a unpredictable moment.

    The solution is to pass the value of toCountryCount to a then of the cy-command that and put the calculation (the for statement) in the .then().