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

Cypress中如何实现同个类不同方法间的变量值传递

实现方案

你可以通过类实例属性存储动态生成的邮箱,两个方法同属一个类的情况下可以直接读写同一个实例属性实现值复用,修改后的代码如下:

class UserManager {
    // 定义类属性存储生成的邮箱
    createdUserEmail = ''

    CreatePrimaryuser() {
        const button = cy.get(':nth-child(2) > a > h3')
        button.click()
        const button1 = cy.get('.btn-edit-user-view')
        button1.click()
        const uemail = cy.get('#emailField')
        const currentDate = new Date();
        const currentTime = currentDate.getTime();
        // 生成邮箱后赋值给类属性
        this.createdUserEmail = 'Automation' + currentTime + '@email.com';
        uemail.type(this.createdUserEmail)
    }
    
    SearchUser() {
        // 直接读取类属性中存储的邮箱进行搜索
        cy.get('#searchUsers').click().type(this.createdUserEmail)
    }
}
注意事项
  • 调用时要保证CreatePrimaryuser方法的执行顺序在SearchUser之前,确保邮箱已经生成并赋值到实例属性
  • 如果需要跨测试用例、跨类复用这个邮箱值,可以将生成的邮箱存入Cypress全局环境变量:赋值时用Cypress.env('createdUserEmail', this.createdUserEmail),取值时用Cypress.env('createdUserEmail')即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 19:09:04