tried to put this in command.js to create a generic function that generates token when login.
const data = require('../fixtures/User_data.json') Cypress.Commands.add('get_token', () => { cy.api({ method: "POST", url: "", body: { "mobile_number": "+91" + data.mobile, "password": "p@ssw0rd" } }) .then((response) => { const token = response.body.data.access_token.token cy.log("Bearer token: " + token ) cy.wrap(token).as('token') }) }) then in my test spec file ,
create_mobilenum () { cy.get_token() cy.api({ method: "POST", url: "", headers: { 'Authorization': "Bearer " + ('@token') }, ... ... but in cypress dashboard , I cannot login because it returns token is undefined when my spec file runs .
1 Answer
From what I've read Variables and Aliases, that's not how to use an alias.
They don't act like variables, you will need to extract the value
cy.get('@token').then(token => { cy.api({ ... headers: { 'Authorization': "Bearer " + token }, 1