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

如何在Cypress中访问Angular验证码组件的属性X

在Cypress测试中访问Angular验证码组件的变量X

问题背景

在Angular项目的验证码组件中,有一个公开的随机变量x,需要在Cypress测试脚本中获取该变量的实际值来完成滑块验证操作。由于测试在生产模式下运行,无法使用window.ng,且不能通过模拟值满足业务需求。

验证码组件代码(captcha.component.ts)

export class CaptchaComponent{
    public x:number; // 每次调用都会生成随机值
};

现有测试脚本(test.cy.ts)

it('login', () => {
    cy.get('#submit-button').click();
    let amountX = ### 如何在此处获取变量x的值
    cy.get('.slider').trigger('mousedown', { button: 0, force: true}).trigger('mousemove', amountX, 100, { force: true}).trigger('mouseup');
});

解决方案

方案1:将变量暴露到全局window对象(需修改组件代码)

在验证码组件的生命周期钩子中,将x变量挂载到全局window对象上,仅在测试环境下执行该逻辑,避免影响生产环境:

export class CaptchaComponent{
    public x:number; 
    
    ngOnInit() {
        // 仅在Cypress测试环境下暴露变量
        if (typeof Cypress !== 'undefined') {
            (window as any).captchaX = this.x;
        }
    }
};

在Cypress脚本中通过cy.window()获取全局变量:

it('login', () => {
    cy.get('#submit-button').click();
    // 等待验证码组件渲染完成
    cy.get('.captcha-component').should('be.visible');
    cy.window().then(win => {
        const amountX = win.captchaX;
        cy.get('.slider')
          .trigger('mousedown', { button: 0, force: true})
          .trigger('mousemove', amountX, 100, { force: true})
          .trigger('mouseup');
    });
});

方案2:通过DOM属性传递变量(无需修改组件逻辑)

在验证码组件的模板中,将x绑定到元素的自定义data-*属性:

<!-- captcha.component.html -->
<div class="captcha-container" [attr.data-captcha-x]="x">
    <!-- 验证码相关DOM元素 -->
</div>

在Cypress脚本中读取该DOM属性的值:

it('login', () => {
    cy.get('#submit-button').click();
    cy.get('.captcha-container').then($container => {
        // 解析属性值为数字
        const amountX = parseInt($container.attr('data-captcha-x') || '0', 10);
        cy.get('.slider')
          .trigger('mousedown', { button: 0, force: true})
          .trigger('mousemove', amountX, 100, { force: true})
          .trigger('mouseup');
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 15:35:21