Home > front end >  Define text value of class as global var, so it can be yield later in Cypress
Define text value of class as global var, so it can be yield later in Cypress

Time:07-14

I want to save text value of class defined inside object as global variable, so it can be yielded outside that object.

What I mean on example - I got:

cy.get(".cat").eq(0).then(text => { let catTitleText = text; cy.wrap(catTitleText).as('catTitleText')});

And I want to use this let catTitleText outside object for URL comparison, so like this:

cy.url().should('eq', Cypress.config().urlLive 'faq.html?category=' catTitleText [...]

But Cypress will throw an error that catTitleText is not defined, which makes sense.

The only solution I've found needs invoking it, like this for example:

cy.get('@catTitleText').then((text) => { function })

But reason I don't want to do this way, is that I want to have multiple variables used inside cy.url() function, so my thinking is to define each variable globally, so those can be invoked in the same manner in cy.url().

Maybe it can be done using invoking but different way in cy.url(), so multiple objects can be yield inside? Sorry if that description is chaotic or I mistaken something, I tried my best to describe it properly.

CodePudding user response:

You can use the Cypress.env() for saving the text and then it can be used throughout your project.

cy.get('.cat')
  .eq(0)
  .invoke('text')
  .then((text) => {
    Cypress.env('catTitleText', text) //Saving the cat title
  })

//Validate URL using Cypress.env
cy.url().should(
  'eq',
  Cypress.config().urlLive   'faq.html?category='   Cypress.env('catTitleText')
)

CodePudding user response:

You can set it an .alias() and use it in junction with function() {} and this keyword.

before(() => {
  cy.get('.cat')
    .eq(0)
    .invoke('text') // get text of element
    .as('cat') //store as alias
})
// use function() {} to be able to use this keyword
it("some test", function() {
  // some more actions

  // get alias using this keyword
  cy.url().should('eq', Cypress.config().urlLive   'faq.htmlcategory='   
     this.cat   ...)
})
  • Related