Lumca
Lumca

Reputation: 183

Storing a value and reuse in another function cypress

I am trying to write a custom command for my app where I create a real user and use its ID in a set of tests.

Since I do test on real BE and DB and I do not stub or mock any data I need to store some values.

The use case is:

  1. I send a request

  2. I get a response with a unique ID

  3. I use this ID in another request and so on...

     cy.request('POST', Cypress.env('active') + 'api/players', {})
     .then((response) => {
       expect(response.status).to.eq(200);
       playerID = response.body.id //<-- i need to store is value and use it below
     });
    
     cy.request('POST', Cypress.env('active') + 'api/kyc/processes', {
       "level": "player",
       "player": playerID, //<-- I need to use it here
       "venue": 1
     });
    

I have tried aliases and they do not work for this. Also, I have tried to define variables outside of the test but it is undefined in another request.

Upvotes: 0

Views: 1464

Answers (2)

Lumca
Lumca

Reputation: 183

I had to resort to writeFile and readFile. It is really dumb but it works. I dont like it though. I think it should be possible to pass data easier trough few requests.

Upvotes: 0

user14783414
user14783414

Reputation:

The problem is the two cy.request() fire off simultaneously.

Using an additional .then() on the first (nesting the second) ensures sequential execution.

cy.request('POST', Cypress.env('active') + 'api/players', {})
.then((response) => {
  expect(response.status).to.eq(200);
  playerId = response.body.id 
  return playerId
})
.then(playerId => {
  cy.request('POST', Cypress.env('active') + 'api/kyc/processes', {
    "level": "player",
    "player": playerId, 
    "venue": 1
  });
});

Upvotes: 1

Related Questions