在我的 DOM 中,我有一个输入和一个 div,我想在一个命令中获取两者的值。
这是一个 HTML 示例
<div id="myDiv">Content of the div</div>
<input id="myInput" value="2000" />
这是我尝试的命令
Cypress.Commands.add("getDomValues", () => {
var divValue = cy.get('#myDiv').invoke('text')
var inputValue = cy.get('#myInput').invoke('val')
return cy.wrap({
divValue:divValue,
inputValue:inputValue
});
});
如果我返回的对象周围没有 cy.wrap,我会收到此错误
Unhandled rejection CypressError: Cypress detected that you invoked one or more cy commands in a custom command but returned a different value.
然后在我现在的测试中我就这样使用它
cy.getDomValues().then((values)=>{
console.log(values)
})
在我的控制台中返回的对象中,我的两个值都有类似的内容
$Chainer {userInvocationStack: " at Context.eval (http://localhost:8888/__cypress/tests?p=cypress/support/index.js:181:24)", specWindow: Window, chainerId: "chainer4419", firstCall: false, useInitialStack: false}
你知道我怎样才能得到这样的结果吗?
{
divValue:"Content of the div",
inputValue:"2000"
}
最佳答案
您需要使用 .then() 访问值
Cypress.Commands.add("getDomValues", () => {
cy.get('#myDiv').invoke('text').then(divValue => {
cy.get('#myInput').invoke('val').then(inputValue => {
// no need to wrap, Cypress does it for you
return {
divValue, // short form if attribute name === variable name
inputValue
}
});
您收到的错误是因为您返回的是Chainers
而不是值。
关于从 DOM 返回值的 Cypress 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68390674/