Cypress中实现循环重置输入直到比较结果不为等号
Cypress循环判断结果直到非“=”的解决方案
问题原因
你的代码仅在第一次检测到结果为“=”时执行了一次reEnterInputs(),但完成重新输入和点击操作后,没有再次触发checkResult()检查新结果,导致逻辑只运行一次就停止。另外Cypress是异步命令式框架,普通函数调用无法保证命令执行顺序,必须利用其命令链特性实现循环逻辑。
解决方案
通过递归调用结合Cypress异步命令链,让checkResult()在处理完“=”的情况后,重新触发检查逻辑,直到结果为“+”或“-”。具体调整点:
- 封装输入随机值并点击比较的逻辑,避免代码重复
- 在
checkResult()的“=”分支中,完成重置、重新输入操作后,递归调用自身实现循环检查
修改后的完整代码
describe('template spec', () => { const numberArray = [0, 1, 2, 3, 4, 5, 6, 7, 8]; it('Check values inside html element', () => { cy.visit('/'); // 初始输入随机值并触发比较 enterRandomValuesAndCompare(); // 启动结果检查循环 checkResult(); }); // 封装:输入随机值 + 点击比较按钮 function enterRandomValuesAndCompare() { const topInput = Math.floor(Math.random() * numberArray.length).toString(); const bottomInput = Math.floor(Math.random() * numberArray.length).toString(); cy.get('#top').type(topInput); cy.get('#bottom').type(bottomInput); cy.get('#compare').click(); } // 递归检查结果,直到非“=”为止 function checkResult() { cy.get('#value') .invoke('text') .then((text) => { if (text === '=') { // 重置输入框 → 重新输入 → 再次检查结果 cy.get('#resetValues').click() .then(enterRandomValuesAndCompare) .then(checkResult); } else { cy.log(`结果为${text},满足条件,停止循环`); } }); } });
代码说明
- 把输入随机值和点击比较的逻辑封装成独立函数,提升代码复用性
checkResult()采用递归方式,每次检测到“=”时,严格按照「重置→重新输入→再次检查」的顺序执行,确保异步操作的等待和顺序- 所有操作都在Cypress命令链中执行,避免出现未完成前置操作就执行检查的问题
内容的提问来源于stack exchange,提问作者Cholis
相关产品推荐
相关产品推荐

