You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cypress中If/Else逻辑失效,CNPJ注册测试循环需求求助

Cypress条件判断失效及循环重试CNPJ解决方案

你的问题核心在于**cy.contains()是断言型命令**,当找不到目标文本时会直接触发超时错误,根本不会进入.then()回调,导致else分支永远无法执行。同时原代码未实现循环重试逻辑,无法满足"直到出现注册确认消息"的需求。

修复思路

  1. 用同步DOM查询(而非断言命令)判断页面是否存在目标文本,避免找不到时直接报错。
  2. 编写递归函数实现循环重试:若检测到"已注册"消息,则更换CNPJ并重新查询,直到出现确认消息后点击确认。

修改后的测试代码

it('Deve cadastrar um CNPJ válido', () => {
    cy.get(':nth-child(2) > .kt-header__topbar-wrapper').click()
    cy.get('.kt-header__topbar-item.show > .dropdown-menu > .kt-notification > .kt-notification__custom').should('be.visible')

    cy.visit('/Company/Create')
    cy.contains('Registration of the Establishment').should('be.visible')

    cy.get(':nth-child(2) > .kt-option > .kt-option__control > .kt-radio > span').click()
    cy.contains('Enter the CNPJ of the establishment you want to add below').should('be.visible')

    // 定义递归函数处理CNPJ查询和状态检查
    const attemptCnpjRegistration = () => {
        cy.get('#searchCnpj')
            .clear()
            .type(faker.br.cnpj())
            .should('be.visible')

        cy.get(':nth-child(2) > .form-group > .input-group > .input-group-append > .btn').click()

        // 同步检查页面文本,避免断言超时
        cy.get('body').then($body => {
            const isAlreadyRegistered = $body.text().includes('Establishment already registered.')
            if (isAlreadyRegistered) {
                cy.log('Estabelecimento já cadastrado. Tentando novo CNPJ...')
                attemptCnpjRegistration() // 递归重试
            } else {
                cy.contains('Do you want to register it?').should('be.visible')
                cy.log('Confirmando registro...')
                cy.contains('Sim').click()
            }
        })
    }

    // 启动第一次尝试
    attemptCnpjRegistration()
})

关键说明

  • 使用cy.get('body').then($body)获取页面DOM,通过$body.text().includes()同步判断文本是否存在,不会因为找不到元素而触发超时。
  • 递归函数attemptCnpjRegistration()实现循环逻辑:每次查询后检查状态,若已注册则重新输入CNPJ并再次查询,直到触发注册确认流程。
  • 避免了原代码中cy.contains()直接断言导致的超时问题,确保条件分支能正常执行。

内容的提问来源于stack exchange,提问作者Gilberto Vieira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 04:08:08