I recently started playing with JS and looking into Cypress to write some simple test automation.
my code writes the following:
Cypress.Commands.add("setup", (email, password) => {
getAccessToken(email, password).then(console.log)
})
function getAccessToken (email, password) {
cy.request('POST', 'testurl',{
"email": email,
"password": password
}).then((response) => {
return response.body.access_token
})
}
console.log prints access_token just fine if I place it within getAccessToken at where the return statement is.. but the console.log prints unidentified if I call it in the command setup even after using .then, (my goal is to get the access_token and use it as an input for another function within "setup")
Your return only returns the response.body.access_token in the Cypress chain. If you added a .then() after the one in your function, you would have correctly yielded the value.
Instead, you can return the entire cy.request() chain in your function, and see the response.
function getAccessToken (email, password) {
return cy.request('POST', 'testurl',{
"email": email,
"password": password
}).then((response) => {
return response.body.access_token
})
}
Tested with this code:
const getTest = () => {
return cy.request('http://www.google.com').then((res) => {
return res.body;
});
};
getTest().then(console.log);