GeorgeEnc
GeorgeEnc

Reputation: 11

Pass variables in Cypress

I'm trying to pass a value from a Cypress custom function to the spec file. The main issue is that the .than() block doesn't assign values to the campaignId variable. What I want is to return wrap(campaignId); and used it in the spec file. From commands file:

Cypress.Commands.add('newCampaignUSP', () => {

  var randomNumber = Math.floor(Math.random() * 1000000);
  var regex = /(\d+)\/edit/;
  var campaignId;

  cy.visit('/' + 'usp/campaign/');
  cy.get('.btn-info:nth-child(1)').click();
  cy.url().should('contains', 'usp/campaign/new');
  cy.get('#tgt_uspbundle_campaign_name').click();
  cy.get('#tgt_uspbundle_campaign_name').type(`automated_test_${randomNumber}`);
  cy.get('#tgt_uspbundle_campaign_geniusTarget').select('0');
  cy.get('#tgt_uspbundle_campaign_saveAndNext').click();
  cy.url({ timeout: 30 * 1000 }).should('include', '/edit/segment');

  cy.url().then((value) => {
    campaignId = value.match(regex); // in this block is created another local campaignId variable
  });

  return cy.wrap(campaignId);
});

Spec file:

describe('USP Campaign Segmentation Browsing', () => {

    before(() => {
        cy.hiveStart();
        cy.login();
    });

    beforeEach(() => {
        cy.preserveAuthCookies();
    });


    after(() => {
        cy.clearLocalStorage();
        cy.clearCookies();
    })

    it('New Campaign', () => {
        cy.newCampaignUSP().then((value) => console.log(value));
    });

Output:

enter image description here

However, in the form below everything works very well:

/// <reference types="Cypress" />

describe('Pass values', () => {

    let url;
    let regex = /(\d+)\/edit/;
    let campaignId;

    before(() => {
        cy.hiveStart();
        cy.login();
    });

    beforeEach(() => {
        cy.preserveAuthCookies();
    });

    after(() => {
        cy.clearLocalStorage();
        cy.clearCookies();
    });

    it('Grab from URL', () => {
        cy.visit('.../usp/campaign/5426/edit/details')

        cy.url().then((value) => {
            url = value;
            campaignId = url.match(regex);
        });
    });

    it('Acces returned URL', () => {
        cy.log(campaignId[1]);
    });
});

Any help will be appreciated! Thank you!

Upvotes: 1

Views: 3099

Answers (1)

Ackroydd
Ackroydd

Reputation: 1610

You can just return the result of cy.url() modified by the .then() clause. This gives a promise, but Cypress automatically waits for it to resolve

Cypress.Commands.add('newCampaignUSP', () => {
  ...

  return cy.url().then((value) => {
    campaignId = value.match(regex); 
    return campaignId
  });
});

cy.newCampaignUSP().then(matchResult => { 
  const campaignId = matchResult[1];
  cy.visit(`/usp/campaign/${campaignId}/edit/template`);
})

WRT to the regex, it's going to set campaignId to an array with various match properties, so I'm not sure that's what you are expecting.

Upvotes: 2

Related Questions