【发布时间】:2019-05-31 13:35:48
【问题描述】:
我需要保存 div 文本值,然后在另一个地方断言?
cy.get('div').should(($div) => {
const myText = $div.innerText
})
cy.get('.value').should('have.text', myText)
【问题讨论】:
标签: javascript testing cypress end-to-end
我需要保存 div 文本值,然后在另一个地方断言?
cy.get('div').should(($div) => {
const myText = $div.innerText
})
cy.get('.value').should('have.text', myText)
【问题讨论】:
标签: javascript testing cypress end-to-end
赛普拉斯是异步的。这意味着如果你这样做:
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)
})
【讨论】:
cy.visit) 命令放入.then() 回调中,这样您就可以访问myText 值。或者,查看我的回答 here 以了解其他解决方法。
你的 sn-p 中的问题是你没有链接它,因此你失去了最后一条语句的价值。基本上,您必须将其链接起来才能在后续步骤中使用。
let tempValue = "";
cy.get('div').each(($div) => {
tempValue = $div.text();
}).then(() => {
cy.get('.value').should('have.text', tempValue)
});
【讨论】:
一种方法是在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();
.....
})
})
【讨论】: