如何保存变量/文本以供稍后在 cypress 测试中使用?

Ken*_*n M 7 javascript cypress

cypress 文档(https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Elements)对于如何在测试期间使用别名和变量来存储信息非常不清楚。

我正在尝试将 div 的文本存储在一页上以供以后使用,例如:

// let vpcName;
    it('Store current name to use later', () => {
    //save name for later use - doesn't work
    // cy.get('#value').then(elem => {
    //   vpcName = Cypress.$(elem).text;
    // });

    //using alias - also doesn't work
    cy.get('#value')
      .invoke('text')
      .as('vpcName');
  });
  it('Use previous value to return to correct page', () => {
    cy.contains(this.vpcName).click();
  });
Run Code Online (Sandbox Code Playgroud)

小智 8

尝试这个:

cy.get('button').then(($btn) => {
  const txt = $btn.text()
  // $btn is the object that the previous command yielded
})
Run Code Online (Sandbox Code Playgroud)

来源:https : //docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Return-Values


new*_*ter 5

我刚刚看到这篇文章,它解释了如何以及为什么存储变量,然后以“柏树方式”使用它:

https://www.stevenhicks.me/blog/2020/02/working-with-variables-in-cypress-tests/

关于它应该如何工作,这是我的示例,首先收集消息(消息仅显示 3 秒然后消失)。其次,它使用“@”符号获取值。最后,我的代码将存储的消息传递给一个空函数,该函数构造为断言值 'Portsmouth' 包含在消息中。

it('Current Port change', () => {
        cy.get('#viewport').find('div[id=message]').then(message => {
            let wags = message;
            cy.wrap(wags).as('wags')
        })
        cy.get('@wags').then(wags => {
        expect(wags).to.contain("Portsmouth")
    })
Run Code Online (Sandbox Code Playgroud)

如果您需要进一步说明,请告诉我

  • “it”语句是测试的声明(或开始)。因此,从技术上讲,2 个“it”语句是 2 个测试,因此它适用于 1 个测试,而不适用于另一个测试。 (2认同)