Cypress: Can I prevent Cypress cy.get from failing if no elements are found?

落爺英雄遲暮 提交于 2019-11-28 04:11:24

问题


I am using Cypress cy.get to grab elements, but if there are none, my test is failing. I do not want it to fail. I want it to continue. The test is simply to list the items that are there, if any.

const listItemTitle = '[data-cy-component=list-item-title]';
cy.get(listItemTitle).each(($el, index, $list) => {
  cy.wrap($el).then(($span) => {
    const spanText = $span.text();
    cy.log(`index: ` + index + ' ' + spanText);
  });
});

I would have thought, if there are no elements there - that this code would still be ok, but not so. When I run it, I get this error: CypressError: Timed out retrying: Expected to find element: '[data-cy-component=list-item-title]', but never found it.

It works fine where elements are present. If no elements are found, I want to go on & do a different test.

Here is an experiment I tried:

let count: number = Cypress.$(listItemTitle).length;
cy.log('before:' + count);
cy.get(actionsBarActionsAdd).click();
cy.get(singlePickerSearch).type('Assets' + '{enter}');
cy.get(listItemCheckboxTitle)
  .first()
  .click();
cy.toast({
  type: 'Success',
});
count = Cypress.$(listItemTitle).length;
cy.log('after:' + count);
cy.get(listItemTitle).each(($li, index, $lis) => {
  cy.log('interface no. ' + (index + 1) + ' of ' + $lis.length);
  cy.wrap($li).click();
});

This was the outcome:

18 LOG        before:0
19 GET       [data-cy-component-key="actions-add"] input
20 CLICK
21 GET       [data-cy-component=single-picker-search] input
22 TYPE      Assets{enter}
23 GET       [data-cy-component="list-item-checkbox-title"]
24 FIRST
25 CLICK
26 GET       .iziToast    toast2
27 ASSERT    expected [ <div.iziToast.iziToast-opening.fadeInUp.iziToast-theme- 
alloy.iziToast-color-green.iziToast-animateInside>, 1 more... ] to have class iziToast-color-green
28 LOG       after:0
29 GET       [data-cy-component=list-item-title]
30 LOG       interface no. 1 of 1

Conclusively shows that Cypress.$(listItemTitle).length does not count number of elements with selector: listItemTitle.

Update:

By putting a cy.wait(1000); after the Add had been executed (in my experiment) - giving the DOM time to update - the new element was found. With more specific selectors, the wait is not required


回答1:


You can use jquery via Cypress.$ to check if any exist.

const listItemTitle = '[data-cy-component=list-item-title]';
if (Cypress.$(listItemTitle).length > 0) {
  cy.get(listItemTitle).each(($el, index, $list) => {
    cy.wrap($el).then(($span) => {
    const spanText = $span.text();
    cy.log(`index: ` + index + ' ' + spanText);
    });
  });
}


来源:https://stackoverflow.com/questions/54150776/cypress-can-i-prevent-cypress-cy-get-from-failing-if-no-elements-are-found

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!