【问题标题】:Cypress command that return values from DOM从 DOM 返回值的赛普拉斯命令
【发布时间】:2021-07-15 08:48:13
【问题描述】:

在我的 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,我会收到此错误

未处理的拒绝 CypressError:赛普拉斯检测到您调用了 自定义命令中有一个或多个 cy 命令,但返回不同的 价值。


然后在我现在的测试中我就这样使用它

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"
}

【问题讨论】:

    标签: cypress


    【解决方案1】:

    您需要使用.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 而不是值。

    【讨论】:

      【解决方案2】:

      您可以使用.as() 分配别名以供以后使用。

      cy.get('#myDiv').invoke('text').as('divValue')
      cy.get('##myInput').invoke('val').as('inputValue')
      

      然后稍后单独使用这些值,例如 -

      cy.get('@divValue').then(divValue => {
        //Do something with div value
      })
      
      cy.get('@inputValue').then(inputValue => {
        //Do something with input value
      })
      

      或者,稍后将这些值一起使用,例如 -

      cy.get('@divValue').then(divValue => {
          cy.get('@inputValue').then(inputValue => {
              //Do something with div value
              //Do something with input value
          })
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-02-26
        • 2021-03-27
        • 2021-07-09
        • 2019-09-14
        • 2022-10-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多