Home > Blockchain >  How to retrieve Token for API calls in cypress
How to retrieve Token for API calls in cypress

Time:03-10

Due to a lack of knowledge in JS, I do face with below problem. I do automation testing with cypress and for external API endpoints, I need to use Dynamic Token that expires every 3600 secs. I did some short research and find out that, for reaching to JWT Token I will need 1st SSO login (that my app has). Then use the below script. But I don't know what to do after this.

 it('the value of JWT Token should exist in localStorage', () => {
        cy.getLocalStorage('JWT_DATA').then(lsData => {
            cy.log('the token', lsData); // I get JWT Token in here
        });
    });

The result of this script is only printing the TOKEN. But I need to store it somehow and then be able to reuse it for every different API endpoint call.

CodePudding user response:

You can use Cypress.env for this. Then you can use the token throughout the test anywhere.

it('the value of JWT Token should exist in localStorage', () => {
  cy.getLocalStorage('JWT_DATA').then((lsData) => {
    cy.log('the token', lsData) // I get JWT Token in here
    Cypress.env('token', lsData)
  })
})

To use it, you can do

Cypress.env('token')
  • Related