【问题标题】:How to get the value for data-id in cypress如何在 cypress 中获取 data-id 的值
【发布时间】:2020-08-08 14:51:08
【问题描述】:

我需要获取 data-id 的值,但是当我使用下面的代码时它没有返回任何值。

cy.get('[data-nemo=token]')
  .invoke('attr', 'data-id').then(dataId => {
    cy.log('dataId : ', dataId);`enter code here`
  });

谢谢,

【问题讨论】:

  • 看起来invoke() 的使用不当。据我从文档中可以看出,它应该类似于cy.get('[data-nemo=token]').getAttribute('data-id')。相关文档:docs.cypress.io/api/commands/get.html#Selector
  • 使用 .getAttribute 时出现错误 - TypeError: cy.get(...).getAttribute() is not a function
  • 页面上有多少元素匹配该选择器?如果get() 返回一个类似对象的数组,您将不得不深入研究如何让元素调用getAttribute on
  • stackoverflow.com/questions/51178736/… 哇,invoke() 的事情我可能完全错了。

标签: jquery attributes cypress invoke


【解决方案1】:

根据 Cypress 文档,您可以使用 cy.invoke 调用 jQuery 方法。所以,就像在 jQuery 中一样,你会这样做

$('[data-nemo=token]').data('id');

在赛普拉斯是

cy.get('[data-nemo=token]').invoke('data', 'id');

如果您想使用该值,您可以使用.then 或使用.as 创建别名并在稍后的测试中引用该别名:

cy.get('[data-nemo=token]')
  .invoke('data', 'id')
  .then(dataId => cy.log('dataId : ', dataId));

cy.get('[data-nemo=token]')
  .invoke('data', 'id')
  .as('dataId');

cy.get('@dataId')
  .then(dataId => cy.log('dataId : ', dataId));

【讨论】:

    【解决方案2】:

    你可以试试下面的代码,看看它是否有效。尝试使用data()attr() 选项来获取id;

    cy.get('[data-nemo=token]').then(($div) => {
            const dataId = Cypress.$($div).attr("data-id");
                // or
            const dataID = Cypress.$($div).data("id");
               // or
            const mydataID = Cypress.$(this).attr("data-id");
            console.log(mydataID);
    });
    

    【讨论】:

    • 上述也没有工作,我仍然没有得到'data-id'的值
    • 请发布该部分的完整 html,如果该部分嵌套在其他 div 中,请从顶部/父级中包含
    • 我已经更新了我的ans,就在控制台记录另一种方法之前,再试一次..如果没有,请发布该部分的完整html
    • 谢谢,但它仍然无法正常工作...我无法粘贴整个 html,所以破坏了它
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签