-1

How can I access the token generated from 1st it block to 2nd it block.

here is the code:

1st it block

      it('Login using new user', () => {
        cy.api({
          method: "POST",
          url:    "https://api-stg.sample.com/v1/user/login",
          body: 
          {
          "mobile_number": "+9912345678"
          "password": "p@ssword"  
          }

        })
          .then((response) => {
            expect(response.status).to.eq(200)
        })
          .then((response) => {
            const bearer_token = response.body.data.user.access_token.token // 
*in here where I get and put the token in var bearer_token*

            cy.log("Bearer token: " + token )
        })
      })

2nd it block

     it('Create New Mobile', () => {
        cy.api({
          method: "POST",
          url:    "https://api-stg.sample.com/v1/user/add_new_mobile_numbers",
          headers: {
            'Authorization': 'Bearer ' + token // *in here where I put the token*
          },
          body: 
          {
            "mobile_prefix": "+991",
            "mobile_number": "9912345679"
          }
})

I login from 1st block, then i need to use the token to add new mobile num in 2nd block.
in cypress dashboard it returns an error: token is not defined

1

1 Answer 1

1

Move the login outside the test, for example, to a before.

You may need to add a condition where it checks if token exists already.

You may also be able to use a before all depending on language and framework.

To use across test files you may wish to consider doing the login in the test runner and setting the token in a way that the framework will expose to individual tests.

As Jon suggested, react the Cypress documentation - it is very good!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.