1

I am struggling with some problems in Cypress when i want to use a variable outside of a method. Let's explain the environment , i got two files, one .spec which is the main for running tests and one .js which is the class where I'm building my methods.

class createCan{
  getRefferal = () => {
    return cy
      .request('someURL')
      .its('body')
      .then((response) => {
        var randomNumber = Math.floor(Math.random() * response.length);
        let referral = response[randomNumber].name;
        return referral;
      });
  };
export default new createClass();

If I want to access referral in my .spec file it says that referral it's undefined/empty.

let referral;
describe("'Create Candidate' tests", () => {
    beforeEach(() => {
     loginPage.login(loginPage.testUsername);
     createClass.getRefferal();
     cy.log(referral);
});

The result of cy.log it's empty :( What should i change to the code so I can be abble to work with value of referral get by that API.

Paracetamol12
  • 35
  • 1
  • 8
  • 1
    Unfortunately the linked question is not useful to you, since Cypress commands are not promises but queued execution commands. See [Commands-Are-Not-Promises](https://docs.cypress.io/guides/core-concepts/introduction-to-cypress.html#Commands-Are-Not-Promises) – Richard Matsen May 16 '20 at 22:24
  • Use an alias within getReferral - `cy.wrap(referral).as('referral')`, then access it like this `beforeEach(function () { cy.log(this.referral) })` (NOTE must use `function()` not `() =>` for valid `this`). See [as()](https://docs.cypress.io/api/commands/as.html#Fixture) – Richard Matsen May 16 '20 at 22:25

0 Answers0