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

如何在Cypress的不同it块中保存并使用Bearer Token?

Cypress保存Bearer Token并跨it块使用的解决方案

原代码的关键问题

  1. 错误使用cy.log().as():cy.log()返回的是日志命令对象,不是token值,无法正确存为alias
  2. 异步执行顺序错误:cy.log(this.Bearer_token)写在then回调外,此时token还未赋值,会输出undefined
  3. 跨it块的作用域问题:默认alias仅在当前it块有效,直接用this.Bearer_token无法在其他it块访问

三种可行解决方案

方案1:使用describe级变量

在describe层级定义变量,将token赋值给该变量,作用域覆盖整个describe下的所有it块,适合单测试文件内共享。

let bearerToken; // 作用域覆盖整个describe

describe('API授权测试', function() {
  // 在所有it块执行前获取token
  before(function() {
    cy.request({
      url: '你的登录接口URL',
      method: 'POST',
      body: {
        userName: 'saurabh.sharma.com',
        password: 'Indigo@123'
      }
    }).its('body').then(body => {
      expect(body.status).to.eq('success');
      bearerToken = body.data.token; // 为全局变量赋值
    });
  });

  it('携带token发起GET请求', function() {
    cy.request({
      url: '需要授权的接口URL',
      method: 'GET',
      headers: {
        'authorization': `Bearer ${bearerToken}`,
        'client-id': '00'
      }
    }).then(res => {
      expect(res.status).to.eq(200);
      const count = res.body.data.totalCount;
      cy.log(`接口返回总条数:${count}`);
    });
  });
});

方案2:使用Cypress环境变量

将token存入Cypress环境变量,可跨测试文件共享,适合多个测试用例需要同一token的场景。

describe('API授权测试', function() {
  before(function() {
    cy.request({
      url: '你的登录接口URL',
      method: 'POST',
      body: {
        userName: 'saurabh.sharma.com',
        password: 'Indigo@123'
      }
    }).its('body').then(body => {
      expect(body.status).to.eq('success');
      Cypress.env('bearerToken', body.data.token); // 存入环境变量
    });
  });

  it('携带token发起GET请求', function() {
    const bearerToken = Cypress.env('bearerToken');
    cy.request({
      url: '需要授权的接口URL',
      method: 'GET',
      headers: {
        'authorization': `Bearer ${bearerToken}`,
        'client-id': '00'
      }
    }).then(res => {
      expect(res.status).to.eq(200);
      const count = res.body.data.totalCount;
      cy.log(`接口返回总条数:${count}`);
    });
  });
});

方案3:使用Alias结合this

通过cy.wrap().as()设置alias,在同describe下的it块中用this.xxx访问,注意必须使用普通function(不能用箭头函数)。

describe('API授权测试', function() {
  before(function() {
    cy.request({
      url: '你的登录接口URL',
      method: 'POST',
      body: {
        userName: 'saurabh.sharma.com',
        password: 'Indigo@123'
      }
    }).its('body.data.token').as('bearerToken'); // 直接为token设置alias
  });

  it('携带token发起GET请求', function() {
    cy.request({
      url: '需要授权的接口URL',
      method: 'GET',
      headers: {
        'authorization': `Bearer ${this.bearerToken}`,
        'client-id': '00'
      }
    }).then(res => {
      expect(res.status).to.eq(200);
      const count = res.body.data.totalCount;
      cy.log(`接口返回总条数:${count}`);
    });
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:15:31