我试图将Cypress元素存储在变量中,然后重新使用它,而不是再次调用get()
。
我第一次失败的尝试:
// works
const wrap = cy.get(`wrapSelector`)
wrap.should('be.visible')
// works
const input = wrap.find(`input`)
input.should('be.focused');
input.type(string);
// wrap is now `input` (line 6) instead of `wrapSelector` (line 2)
const button = wrap.find('button').click();
// @error: button not found in `input`
因此,我已经阅读了赛普拉斯的闭包,并且我尝试使用then()
。但是它返回jQuery对象。
cy.get(`someSelector`).then($wrap=>{
// now I would like to test $wrap
// but $wrap is now jQuery object so I can't do this:
$wrap.should('be.visible')
// ... some code
})
如果我对孩子使用整个选择器,可能会起作用,但是我不确定这是否是最佳实践
cy.get(`wrapSelector`).should('be.visible')
cy.get(`wrapSelector input`).should('be.focused')
cy.get(`wrapSelector input`).type(string);
cy.get(`wrapSelector button`).click()
// works
我知道我也可以测试jQuery对象(例如,使用expect()
),但是我想继续使用should()
。当我想重用一些已经获取的元素时,最佳实践是什么?此示例的理想解决方案是最好的。
答案 0 :(得分:2)
您应该使用赛普拉斯在此处提到的别名:https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Sharing-Context
由于使用了promise,因此Cypress方法不会直接返回值。别名允许您:
cy.get(element).as("myAlias")
this.myAlias // works
cy.get("@myAlias") // works