赛普拉斯:查找元素数量而不会引发错误

时间:2019-06-25 12:28:07

标签: javascript cypress

我需要找到具有给定定位符(cy.get()或cy.xpath())的网页上存在的元素数。如果指定的定位器中没有该元素,则不应使测试失败。

我尝试了cy.get(),cy.find(),cy.xpath():如果在网页上找不到该元素,它们都将通过测试。 我试图使用cy.get('body')。find('loc')。length; 但它也未通过测试。

以下代码有效,但是我无法在循环外使用x的值。场景就是这样,我无法将所有代码都放在then()中。

let x = 0;
 cy.get("body").then(($body) => {
 x = $body.find("element").length;
 cy.log(`inside then: `,x);
})
cy.log(`outside then: `,x);

预期: 然后里面:,1 在外面:,1

实际: 然后里面:,1 在外面:,0

3 个答案:

答案 0 :(得分:1)

您可以尝试使用.its()函数来检索length属性的值:

cy.get("body").its("length");

答案 1 :(得分:0)

let x = 0;
 cy.get("body")
.then( 
  ($body) => {
  x = $body.find("element").length;
  cy.log(`inside then: `,x);
})
.then( 
  () => {
  cy.log(`outside then: `,x);
} )

您需要在x = $ body.find(“ element”)。length;处等待x更新。
事件循环如下所示:
1.令x = 0;
2. cy.log('outside then:',x); -x = 0;
3. x = $ body.find(“ element”)。length;
4. cy.log('inside then:',x);

答案 2 :(得分:0)

不清楚您要实现什么,但是我想您要测试可用元素总数。如果没有,那就不应该出错。如果正确,那么这可能会有所帮助:

let x = 0;
function anyName() {
  return cy.get("body").then($body => {
    x = $body.find("element").length;
    if (x > 0) {
      cy.log(`Total no of elements found: ${x}`);
    } else {
      cy.log("Element is not available");
    }
  });
}
anyName();