Liran H
Liran H

Reputation: 10579

How to pass variable from .within() to .then()?

I want to pass foo from .within() to .then(). I expected the following code to work, but it doesn't. foo ends up being a jQuery element. Is there a way to do this?

cy.get('.some-selector')
    .within(() => {
        const foo = 'Some value'
        return foo
    })
    .then((foo) => {
        console.log(foo)
    })

Upvotes: 0

Views: 491

Answers (1)

user16695029
user16695029

Reputation: 4440

Cypress docs talk about back-flips, which is where an external variable is set by a command callback.

It's warned against, but in this case will work because setting and using are both within sequenced steps.

let foo
cy.get('.some-selector')
  .within(() => {
    foo = 'Some value'
  })
  .then(() => {
    expect(foo).to.eq('Some value')
  })

Upvotes: 2

Related Questions