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

Cypress API测试:如何在不同it块间传递生成的Token

解决Cypress跨it块共享Bearer Token的问题

问题根源

  1. 变量作用域限制:第一个it块中定义的bearer_token是局部变量,仅在当前then回调的作用域内有效,第二个it块无法直接访问。
  2. 变量名笔误:第一个it块中定义的变量是bearer_token,但cy.log里误用了未定义的token,这也是一处错误。

解决方法

下面提供两种可靠的跨it块共享Token的方案:

方案1:使用Cypress环境变量(推荐)

环境变量是Cypress全局可用的存储方式,适合跨测试用例共享数据。

修改第一个it块,将Token存入环境变量:

it('Login using new user', () => {
  cy.api({
    method: "POST",
    url:    "https://api-stg.sample.com/v1/user/login",
    body: {
      "mobile_number": "+9912345678",
      "password": "p@ssword"  
    }
  })
  .then((response) => {
    expect(response.status).to.eq(200)
    const bearer_token = response.body.data.user.access_token.token
    cy.log("Bearer token: " + bearer_token) // 修正变量名错误
    Cypress.env('bearerToken', bearer_token) // 将Token存入全局环境变量
  })
})

第二个it块读取环境变量并使用:

it('Create New Mobile', () => {
  cy.api({
    method: "POST",
    url:    "https://api-stg.sample.com/v1/user/add_new_mobile_numbers",
    headers: {
      'Authorization': 'Bearer ' + Cypress.env('bearerToken') // 读取全局环境变量
    },
    body: {
      "mobile_prefix": "+991",
      "mobile_number": "9912345679"
    }
  })
})

方案2:使用Cypress别名

通过cy.wrap().as()设置别名,在第二个it块中通过cy.get('@别名')获取Token,注意要处理异步逻辑。

第一个it块设置别名:

it('Login using new user', () => {
  cy.api({
    method: "POST",
    url:    "https://api-stg.sample.com/v1/user/login",
    body: {
      "mobile_number": "+9912345678",
      "password": "p@ssword"  
    }
  })
  .then((response) => {
    expect(response.status).to.eq(200)
    const bearer_token = response.body.data.user.access_token.token
    cy.log("Bearer token: " + bearer_token)
    cy.wrap(bearer_token).as('bearerToken') // 为Token设置别名
  })
})

第二个it块通过别名获取Token:

it('Create New Mobile', () => {
  cy.get('@bearerToken').then(token => { // 异步获取别名对应的Token
    cy.api({
      method: "POST",
      url:    "https://api-stg.sample.com/v1/user/add_new_mobile_numbers",
      headers: {
        'Authorization': 'Bearer ' + token
      },
      body: {
        "mobile_prefix": "+991",
        "mobile_number": "9912345679"
      }
    })
  })
})

注意事项

  • 确保测试用例按顺序执行:Cypress默认按代码顺序执行it块,所以登录用例必须在新增手机号用例之前。
  • 避免使用普通全局变量:Cypress的测试用例是在独立的上下文执行的,普通全局变量可能无法在it块之间共享。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 10:07:34