I am trying to call an endpoint using cypress and get a value out form the JSON body. I am able to console.log(response.body.data.invitationCode)
out fine but can't seem to assign that value to a variable (I want to pass that value to subsequent requests). I've tried using promises but I still can't get the value.
Here is my code:
/// <reference types="cypress" />
const faker = require('faker');
// We can change this to an ENV variable if we want to run this in different environments
const baseURL = 'https://<my url>/';
const user = {
createUser: async function () {
let code;
await user.waitListEndpointCall().then((response) => {
{
//console.log(response.body.data.invitationCode) works like a charm
code = response.body.data.invitationCode;
}
});
console.log(code); //doesn't work
},
/**
* Function calls the '/api/v1/public/waitList/post' and returns an invitation code
*/
waitListEndpointCall: function () {
const options = {
method: 'POST',
url: `${baseURL}/api/v1/public/waitList/post`,
body: {
email: `dmtest-${faker.random.number(1000001)}@gmail.com`,
},
};
return cy.request(options);
// return new Cypress.Promise((resolve, reject) => {
// cy.request(options).then((response) => resolve(response));
// });
},
};
module.exports = {
user,
};
console.log(code)
gives me undefined
in cypress.
I've even wrapped my cy.request
in a promise like so:
waitListEndpointCall: function(){
const options: {
...
}
return new Cypress.Promise((resolve, reject) => {
cy.request(options).then((response) => resolve(response));
});
}
calling it like via:
let res = await user.waitListEndpointCall();
console.log(res.body);
and I still get undefined