0

i make an api request to get the token and use it in another function in a seprate file, when i export the token from one file to another it is not working as expected , the activat user method can not read the token

my code in one file

class User {

  user_T= ''

  getaccessToken(){

    cy.request({

        method: 'POST',
        url: 'url',
        form: true,
        body: {
          
          "username": .,..
          "password": ....
  
        }
      })
      .then( response=> {
         
          return this.user_T= response.body.Token;
      })
  }
}

export default new User

the other file is

import User from './user'

const token= new User()


it.only('activate user', () => {
  
    cy.request({
      
      method: "POST",
      url: 'url/activate',
      headers: {
        'Authorization' : 'Bearer ' + token.user_T,
      
    },
      body:{
       "test": 'test'
      } 
    }) 
   
  }) 
agoff
  • 5,818
  • 1
  • 7
  • 20
soso
  • 1

1 Answers1

0
  1. You do not need to return this.user_T= response.body.Token; in your .then() block. If you are setting the value of this.user_T, then you can just do that. If you want to return the value of response.body.Token so that you can assign it a value, you can just do that. But doing both, while not causing any issues with how you are using it currently, is not the correct way.
.then((response) => {
  this.user_T = response.access.Token
});
// or
.then((response) => {
  return response.access.Token
});

If you are returning the value from the .then(), you'll also have to return the entire cy.request() command chain.

  1. getaccessToken is the function that actually generates a non-empty string value for user_T. In order to have user_T not equal an empty string, you'll need to call that function.
// Assuming you are still setting the `user_T` value instead of returning it
import User from './user'

const user = new User()

it.only('activate user', () => {
  user.getaccessToken().then(() => {
    cy.request({
      
      method: "POST",
      url: 'url/activate',
      headers: {
        'Authorization' : 'Bearer ' + user.user_T,
    },
      body:{
       "test": 'test'
      } 
    }) 
  })
})
agoff
  • 5,818
  • 1
  • 7
  • 20