问题描述
以下代码在测试中运行良好。
cy.get("table").find(`tr[data-index=0] > :nth-child(1)`).then($td => {
cy.get("input").type($td.text().trim() + "{enter}");
});
const getResult = () => {
cy.get("table",{timeout: 60000}).find(`tr[data-index=0] > :nth-child(1)`,{timeout: 60000}).then($td => {
return $td.text().trim()
});
}
it("query",() => {
cy.get("input").type(getResult() + "{enter}");
})
我对柏树中的 then()
遗漏了什么?
当然,目的是获取表格第一个单元格的内容并将其输入到 input
字段中。
编辑:
按照@jean-smaug 的建议,我尝试了这个 invoke/as
但我收到错误 Cannot read property 'text' of undefined
。实际上,该函数位于不同的 ES 模块中,上下文也不同。代码:
// different ES module
export const getResult = () => {
cy.get("table").find(`tr[data-index=0] > :nth-child(1)`).invoke("text").as("text")
}
// test
getResult("opencga-file-grid")
cy.get("input").type(this.text + "{enter}");
解决方法
如果您删除别名并将返回值视为 Cypress Chainable,则您的最后一个示例有效。
// different ES module
export const getResult = () => {
return cy.get("table").find(`tr[data-index=0] > :nth-child(1)`).invoke("text");
}
// test
getResult("opencga-file-grid")
.then(text => {
cy.get("input").type(text + "{enter}");
});
相当于这个(如果所有代码都在同一个文件中)
cy.get("table").find(`tr[data-index=0] > :nth-child(1)`).invoke("text")
.then(text => {
cy.get("input").type(text + "{enter}");
});
,
的问题是如何在赛普拉斯访问变量。
该文档的这部分应该是有益的
https://docs.cypress.io/guides/core-concepts/variables-and-aliases.html#Sharing-Context
我想你可以做这样的事情。
cy.get("table",{timeout: 60000}).find(`tr[data-index=0] > :nth-child(1)`,{timeout: 60000}).invoke('text').as('text')
cy.get("input").type(this.text + "{enter}");