[英]How Do I Store A Value In Cypress For Later Use Within A Test?
Problem: I am testing whether one piece of information is exactly the same as it is somewhere else.问题:我正在测试一条信息是否与其他地方的信息完全相同。 I would like to know how to keep that first piece of information, and then use it later for comparison through Cypress assertions.
我想知道如何保留第一条信息,然后稍后通过赛普拉斯断言将其用于比较。
Steps for extra clarity of problem:使问题更加清晰的步骤:
cy.get()
to obtain an element in the HTML DOMcy.get()
获取HTML DOM中的一个元素 Current Code Attempt:当前代码尝试:
// After visiting the first URL, I look to store the display title:
cy.get('[datacy="displayTitle"]').then((displayTitle) => cy.wrap(displayTitle).as('displayTitle'));
// I then go to the second url
cy.visit("different url")
// My attempt at asserting the first element equals the second.
cy.get("@displayTitle").then(title => {
const titleText = cy.get(':nth-child(1) > .css-106jpu6 > .css-1j088rq > .MuiBox-root > button > .MuiTypography-root')
expect(title).to.equal(titleText)
})
Error:错误:
(uncaught exception)TypeError: Cannot read properties of null (reading 'displayTitle')
It looks like I cannot read the properties when wrapping the display title, to make the assertion.看起来我在包装显示标题时无法读取属性来做出断言。 What am I doing incorrectly?
我做错了什么? Is wrapping the best approach here?
包装是最好的方法吗?
The solution is to use cy.wrap()
, and access the value of the element.解决方案是使用
cy.wrap()
,并访问元素的值。 This removed my error.这消除了我的错误。
Read about wrap in the Cypress documentation .在Cypress 文档中阅读有关 wrap 的内容。
Step 1) Wrap the first element you would like to use later, and use the val()
method to target the value of the element:步骤 1)包装您稍后要使用的第一个元素,并使用
val()
方法定位元素的值:
cy.get('element').then((el) => cy.wrap(el.val()).as('el'));
Step 2) Navigate to your new page:步骤 2)导航到您的新页面:
cy.visit(url)
Step 3) Compare the first value with the value on that page:步骤 3)将第一个值与该页面上的值进行比较:
cy.get('secondElement').then((secondEl) => cy.wrap(secondEl.val()).as('secondEl'));
cy.get("@secondElement").then((secondElement) => cy.get("@el").should("contain", secondElement));
Code Samples Altogether:代码示例总计:
cy.get('element').then((el) => cy.wrap(el.val()).as('el'));
cy.visit(url)
cy.get('secondElement').then((secondEl) => cy.wrap(secondEl.val()).as('secondEl'));
cy.get("@secondElement").then((secondElement) => cy.get("@el").should("contain", secondElement));
In addition to the options already mentioned, there is also the option of using Cypress environment variables .除了已经提到的选项之外,还有使用赛普拉斯环境变量的选项。
The use is very simple:使用非常简单:
Set variable:设置变量:
Cypress.env(ENV_NAME, yourVariable)
Read variable:读取变量:
const yourVariable = Cypress.env(ENV_NAME)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.