How to work with multiple variables in Cypress?

Viewed 630

tl;dr: can cypress variables be stored in some accesible place (like this or something similar) or do I have to get into an endless callback cycle if I want to access all of them for a single usage?

Long story:

the app I'm trying to cover with cypress tests runs on many different datasets so in order to prepare the test data before the test, I usually make few API calls and I'd like to work with their results:

Example:

The test should cover a "delete task" functionality. As test data, I want to create a task beforehand over our API. To do this, I need to make these calls:

  1. Call ".../users/me" to get my userId (one of required params)
  2. Call ".../users" to get a list of all users for particular dataset (first id is used to filter another, that is then used for assigneeId, another required param)
  3. Call ".../tasks" with previous id's as required parameters

I currently have custom commands that handle those specific api calls while returning the result. I then call those commands and save their return as cypress variable. Should I want to do the third api call, I have to do something like this:

    cy.getUserID().then((userId) => {
      cy.wrap(userId).as('userId')
    })
    cy.getAllUsersForTenant().then((users) => {
      cy.get('@userId').then((userId) => {
        const result = users.find((escalationUserId) => escalationUserId !== userId)
        cy.wrap(result.id).as('assigneeId')
      })
    })


    cy.get('@assigneeId').then((assigneeId) => {
      cy.get('@userId').then((userId) => {
        // do the POST call with both assigneeId and userId available
      })
    })

Right now it's not really a big deal but I can imagine that I'l need more than 2 variables, will I have to add more nested callbacks or is there a way to store those variables at one accessible place?

1 Answers

I sort of figured it out by looking at other tickets - if I use function() instead of arrow functions, it is possible to share this context.

Related