How can I save the bearer token and use it in another ‘IT’ blocks? please help I am new to cypress and JavaScript.
let Bearer_token
describe(‘get new API,function (){
it("get api request", function(){
cy.request({
url : 'whatever url',
method : "POST",
body : {
userName : 'saurabh.sharma.com',
password : 'Indigo@123'
}
}).its('body').then((body) => {
expect(body.status).to.eq('success')
let A_token = body.data.token
// cy.wrap(A_token).as('Bearer_token')
cy.log(body.data.token).as('Bearer_token')
})
cy.log(this.Bearer_token)
cy.request({
url: 'whatever url',
method: "GET",
headers: {
'authorization': 'Bearer ' + this.Bearer_token,
'client-id': '00'
}
}).then((res)=>{
expect(res.status).to.eq(200)
var count = res.body.data.totalCount
cy.wrap(count).as('count')
})
cy.log(this.count)
})
3
Answers
See the hooks section of the Writing tests page in the documentation.
Use a
before
hook to fetch the bearer token and assign it to a variable in the top level scope of the test module.You can use the
Cypress.env
variable to save and use the token globally –The alias method is correct, but don’t use it in conjunction with
cy.log()
as that command does not return the value logged.To use the alias in further tests, use the same
function()
format