Cypress: I want to GET data from JSON and pass it as parameter for other tests

Viewed 132

I have a POST request for login. It returns a JSON with an "accessToken". In order to perform future REST calls I have to use the "accessToken" in the header as Authorization.

So I created a command like:

Cypress.Commands.add('authToken', () => {
 
  it('POST test for Login', function(){
        
    cy.request({

        method : 'POST',
        url : 'myWebsite',
        body: {
            "client_id": "DATA1",
            "username": "DATA2",
            "password": "DATA3"
        },
        
        headers:{
            'Content-Type' : 'application/json',
            'Accept' : 'application/json',
        }
    }).then(function(response){
         // the body returned is a Json which has a parent ticket with a Key = access_token
        // HERE I tried different things: 
        let auth 
        auth = response.body.ticket.access_token
        return auth 
        
        // or 
        cy.wrap(response.body.ticket.access_token)

        // or
        
        return response.body.ticket.access_token

....

In the test I want to use the returned access_token:

describe('GET members', function(){
    
    it('GET members', function(){

        let val = cy.authToken()

        cy.request({
            method : 'GET',
            url : 'myWEb',
            
            headers:{
                'Content-Type' : 'application/json',
                'Accept' : 'application/json',
                "Authorization" : val,
            }
        ....
0 Answers
Related