Home > Mobile >  How to save API Token to use later in Cypress test?
How to save API Token to use later in Cypress test?

Time:10-26

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
    
  })})
  
})

CodePudding user response:

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
    });
  });
});

CodePudding user response:

Another approach would be to create the access_token in a hook and then you can access it in a it() block.

There are a few ways to do it.

Using variable:

let text
beforeEach(() => {
  cy.wrap(null).then(() => {
    text = "Hello"
  })
})

it("should have text 'Hello'", function() {
  // can access text variable directly
  cy.wrap(text).should('eq', 'Hello')
})

Using an alias:

beforeEach(() => {
  cy.wrap(4).as("Number")
})

it("should log number", function() {
  // can access alias with function() and this keyword
  cy.wrap(this.Number).should('eq', 4)
})

Here is a working example.

  • Related