首页 > 解决方案 > 我如何等待列表中的每个元素使用 cypress 更新为特定文本

问题描述

假设我有一个包含不同颜色项目的列表。如果我添加参数,该列表可以更新为仅列出蓝色项目。如何验证每个项目是否正确?

cy.addParameter('blue'); //Will send graphQL query to fetch the correct items. 

cy.get('data li').each((item)=> {
         cy.wrap(item).should('have.text', ' blue ');
       });

这将失败,因为在我有可能检查每个项目之前,列表中的项目尚未更新。可以等待请求完成,但由于查询在第一次运行后保存,“检查”第二次将不起作用。

标签: javascriptcypressui-testing

解决方案


您必须编写一个递归承诺函数并自己检查彩色文本,尝试以下

function checkColor(selector, color, maxWait, alreadyWaited = 0) {
  const waitTime = 500;
  // cy.get returns a thenebale
  return cy.get(selector).each((item)=> {
    // it checks the text right now, without unnecessary waitings
    if(!item.text() === color) {
      return false;
    }
    return true;
  }).then(result => {
    if(result) {
      // only when the condition passes it returns a resolving promise
      return Promise.resolve(true);
    }
    // waits for a fixed milliseconds amount
    cy.wait(waitTime);
    alreadyWaited++;
    // the promise will be resolved with false if the wait last too much
    if(waitTime * alreadyWaited > maxWait) {
      return Promise.reject(new Error('Awaiting timeout'))
    }
    // returns the same function recursively, the next `.then()` will be the checkColor function itself
    return checkColor(selector, color, maxWait, alreadyWaited);
  });
}

// then, in your test...
cy.addParameter('blue'); //Will send graphQL query to fetch the correct items. 
checkColor('data li', 'blue', 10000).then(result => {
  cy.get('data li').each((item)=> {
    cy.wrap(item).should('have.text', ' blue ');
  });
  // or
  expect(result).to.be(true);
});

我试图尽可能多地评论代码重构我为接受的类似问题开发的代码。

如果您需要更多帮助,请告诉我

更新

我们(Tommaso)编写了一个插件来帮助你进行这种检查,它的名字是cypress-wait-until

请为此感谢开源星期六社区,我们在其中一个星期六开发了它


推荐阅读