javascript - 我如何等待列表中的每个元素使用 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 ');
});
这将失败,因为在我有可能检查每个项目之前,列表中的项目尚未更新。可以等待请求完成,但由于查询在第一次运行后保存,“检查”第二次将不起作用。
解决方案
您必须编写一个递归承诺函数并自己检查彩色文本,尝试以下
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。
请为此感谢开源星期六社区,我们在其中一个星期六开发了它
推荐阅读
- python - Python 多线程休息 API
- javascript - 类型错误:无法读取未定义的属性“角色”|| 不和谐.js
- c# - 光标闪烁改变直到重新启动
- ios - Swift 包:致命错误:找不到名为的包
- python - Python模拟对不记名令牌的请求?
- spring-boot - 如何在spring boot(2.4.2)生成的docker镜像中覆盖application.yml中的配置?
- amazon-web-services - 在 EC2 上创建虚拟声卡
- optimization - Julia - 生成 2 个匹配的奇数集
- typescript - 在方法中使用 keyof 来输入参数
- python - Dash Plotly - dbc.Button n_clicks 回调不起作用