如何保存div文本以在其他地方使用?

时间:2019-05-31 13:35:48

标签: cypress

我需要保存div文本值并在另一个地方断言之后吗?

cy.get('div').should(($div) => {
    const myText = $div.innerText
})
cy.get('.value').should('have.text', myText)

3 个答案:

答案 0 :(得分:0)

Cypress是异步的。这意味着如果您执行以下操作:

cy.get('div').should(($div) => {
  const myText = $div.innerText
})
cy.get('.value').should('have.text', myText)

...您的测试将始终失败。 const myText = $div.innerText将在评估.should('have.text', myText)后执行。

如果您想以这种方式使用myText,只需使用cy.get()返回的Promise:

cy.get('div')
.then($div => {
  const myText = $div.text()
  // write the rest of your test here
  cy.get('.value').should('have.text', myText)
})

答案 1 :(得分:0)

您的代码段中的问题是您没有链接它,因此丢失了最后一条语句的值。基本上,您必须将其链接起来才能在后续步骤中使用。

let tempValue = "";
cy.get('div').each(($div) => {
  tempValue = $div.text();
  }).then(() => {
       cy.get('.value').should('have.text', tempValue)
});

答案 2 :(得分:0)

commands.js文件中编写简单的javascript函数并返回text的一种方式。 现在,您可以随时随地调用commands.js函数。

/ cypress / support / commands.js

Cypress.Commands.add('getText', () => {
 cy.visit('/');
 cy.get('div')
  .then($div => {
  const myText = $div.text();
    return myText;
  })
});

//这是您的测试文件1,例如'test-spec-1.js'

describe('Test spec-1', function() {
  it('Receive first time ', function() {
   cy.visit('/');
   const someText1 = cy.getText(); 
...
  })
})

//这是您的测试文件2,例如'test-spec-2.js'

describe('Test spec-2', function() {
  it('Receive second time', function() {
   cy.visit('/');
   const someText2 = cy.getText(); 
.....
  })
})
相关问题