[英]How Do I Store A Value In Cypress For Later Use Within A Test?
問題:我正在測試一條信息是否與其他地方的信息完全相同。 我想知道如何保留第一條信息,然后稍后通過賽普拉斯斷言將其用於比較。
使問題更加清晰的步驟:
cy.get()
獲取HTML DOM中的一個元素當前代碼嘗試:
// 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)
})
錯誤:
(uncaught exception)TypeError: Cannot read properties of null (reading 'displayTitle')
看起來我在包裝顯示標題時無法讀取屬性來做出斷言。 我做錯了什么? 包裝是最好的方法嗎?
解決方案是使用cy.wrap()
,並訪問元素的值。 這消除了我的錯誤。
在Cypress 文檔中閱讀有關 wrap 的內容。
步驟 1)包裝您稍后要使用的第一個元素,並使用val()
方法定位元素的值:
cy.get('element').then((el) => cy.wrap(el.val()).as('el'));
步驟 2)導航到您的新頁面:
cy.visit(url)
步驟 3)將第一個值與該頁面上的值進行比較:
cy.get('secondElement').then((secondEl) => cy.wrap(secondEl.val()).as('secondEl'));
cy.get("@secondElement").then((secondElement) => cy.get("@el").should("contain", secondElement));
代碼示例總計:
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));
除了已經提到的選項之外,還有使用賽普拉斯環境變量的選項。
使用非常簡單:
設置變量:
Cypress.env(ENV_NAME, yourVariable)
讀取變量:
const yourVariable = Cypress.env(ENV_NAME)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.