Tes*_*ter 2 javascript ui-testing cypress
让\xc2\xb4s 说我有一个包含不同颜色的项目的列表。如果我添加参数,该列表可以更新为仅列出蓝色项目。如何验证每一项是否正确?
\n\ncy.addParameter(\'blue\'); //Will send graphQL query to fetch the correct items. \n\ncy.get(\'data li\').each((item)=> {\n cy.wrap(item).should(\'have.text\', \' blue \');\n });\nRun Code Online (Sandbox Code Playgroud)\n\n这将失败,因为在我可以检查每个项目之前列表中的项目尚未更新。可以等待请求完成,但由于查询在第一次运行后保存,因此“检查”第二次将无法工作。
\n您必须编写一个递归承诺函数并自行检查颜色文本,尝试以下操作
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);
});
Run Code Online (Sandbox Code Playgroud)
我尝试尽可能多地评论代码,重构我为接受的类似问题开发的代码。
如果您需要更多帮助,请告诉我
更新
我们(我和Tommaso)编写了一个插件来帮助您进行此类检查,其名称为cypress-wait-until。
请为此感谢开源周六社区,我们在其中一个周六开发了它
| 归档时间: |
|
| 查看次数: |
4483 次 |
| 最近记录: |