Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to retrieve Token for API calls in cypress

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading