如何在Cypress中终止.each循环,仅执行单次测试?
解决Cypress中each循环无法终止的问题
问题原因
你用return false无法终止cy.get('app-product').each()循环,是因为内部的cy.wrap($product).find(...).then(...)是异步命令:each循环是同步遍历所有元素的,只是把异步命令加入Cypress的命令队列,当then里的return false执行时,each循环已经完成了全部遍历,所以无法终止。
解决方案
方法一:直接定位目标元素(推荐,效率最高)
不用遍历所有元素,直接通过过滤找到第一个符合条件的app-product元素:
it.only('Checks "Billing" -> invoice section when products are added', () => { // 同步过滤出第一个包含值为"productName"的输入框的app-product cy.get('app-product').filter((index, el) => { const $input = Cypress.$(el).find('input.product-name').first(); return $input.length > 0 && $input.val() === 'productName'; }).first().then(($product) => { // 执行目标操作 cy.wrap($product) .find('.column-elem.amount .nav-item.actions i-feather[name="more-vertical"].dropdown-toggle') .click(); Elements.getButtonInDropdownMenu(Translations.get('BILLINGS.COPY')) .scrollIntoView() .click({force: true}); Permission.isAccessDeniedActionDone(); Permission.closeAccessDeniedModal(); }); });
方法二:用标志变量控制循环终止
如果需要保留遍历逻辑,可通过同步判断+标志变量来终止each循环:
it.only('Checks "Billing" -> invoice section when products are added', () => { let targetFound = false; cy.get('app-product').each(($product) => { // 已找到目标,终止循环 if (targetFound) return false; const $input = $product.find('input.product-name').first(); if ($input.length > 0 && $input.val() === 'productName') { targetFound = true; // 执行目标操作 cy.wrap($product) .find('.column-elem.amount .nav-item.actions i-feather[name="more-vertical"].dropdown-toggle') .click(); Elements.getButtonInDropdownMenu(Translations.get('BILLINGS.COPY')) .scrollIntoView() .click({force: true}); Permission.isAccessDeniedActionDone(); Permission.closeAccessDeniedModal(); } }); });
注意:这里直接用jQuery的val()同步获取输入框值,避免了异步then导致的判断滞后问题,确保标志变量能及时生效终止循环。
内容的提问来源于stack exchange,提问作者Arto Avag
相关产品推荐
相关产品推荐

