Search code examples
google-chromeautomated-testscypress

How to save API Token to use later in Cypress test?


I have this code to use saved API token and use it on other test, but it doesn't work (I get this error message : Reference Error : access_token is not defined: so I need to save my generated token and use it on all my API test

const API_STAGING_URL = Cypress.env('API_STAGING_URL')

describe('Decathlon API tests', () => {
it('Get token',function(){
cy.request({
  method:'POST',
  url: 'https://test.com/as/token.oauth2?grant_type=client_credentials',
  headers:{
    authorization : 'Basic 1aFJueHkxddsvdvsdcd3cSA=='
  }}).then((response)=>{
    expect(response.status).to.eq(200)
    const access_token = response.body.access_token
    cy.log(access_token)
    cy.log(this.access_token)
  })
  cy.log(this.access_token)
}),

it('Create Cart',function(){      
cy.request({
  method:'POST',
  url: `${API_STAGING_URL}`+"/api/v1/cart",
  headers:{
    Authorization : 'Bearer ' + access_token,
    "Content-Type": 'application/json',
    "Cache-Control": 'no-cache',
    "User-Agent": 'PostmanRuntime/7.29.2',
    "Accept": '*/*',
    "Accept-Encoding": 'gzip, deflate, br',
    "Connection": 'keep-alive',
    "Postman-Token": '<calculated when request is sent>'

  },
      
            
  }}).then((response)=>{
    //Get statut 200
    expect(response.status).to.eq(200)
    //Get property headers
    
  })})
  
})

Solution

  • This is a scoping issue - access_token does not exist outside of the block where it is created. Filip Hric has a great blog post on using variables with Cypress. My favorite strategy would be to store the value in a Cypress environment variable.

    const API_STAGING_URL = Cypress.env('API_STAGING_URL');
    
    describe('Decathlon API tests', () => {
      it('Get token', function () {
        cy.request({
          method: 'POST',
          url: 'https://test.com/as/token.oauth2?grant_type=client_credentials',
          headers: {
            authorization: 'Basic 1aFJueHkxddsvdvsdcd3cSA=='
          }
        }).then((response) => {
          expect(response.status).to.eq(200);
          Cypress.env('access_token', response.body.access_token);
          cy.log(Cypress.env('access_token'));
        });
      });
    
      it('Create Cart', function () {
        cy.request({
          method: 'POST',
          url: `${API_STAGING_URL}` + '/api/v1/cart',
          headers: {
            Authorization: `Bearer ${Cypress.env('access_token')}`,
            'Content-Type': 'application/json',
            'Cache-Control': 'no-cache',
            'User-Agent': 'PostmanRuntime/7.29.2',
            Accept: '*/*',
            'Accept-Encoding': 'gzip, deflate, br',
            Connection: 'keep-alive',
            'Postman-Token': '<calculated when request is sent>'
          }
        }).then((response) => {
          // Get statut 200
          expect(response.status).to.eq(200);
          // Get property headers
        });
      });
    });