首页 > 解决方案 > 如何将变量从 .within() 传递给 .then()?

问题描述

我想foo.within().then()。我希望以下代码可以工作,但事实并非如此。foo最终成为一个 jQuery 元素。有没有办法做到这一点?

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

标签: cypress

解决方案


赛普拉斯文档谈论后空翻,这是由命令回调设置外部变量的地方。

警告不要这样做,但在这种情况下会起作用,因为设置和使用都在顺序步骤中。

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


推荐阅读