如何保存API Token以便稍后在Cypress测试中使用?

问题描述 投票:0回答:3

我有这段代码可以使用保存的API令牌并在其他测试中使用它,但它不起作用(我收到此错误消息:参考错误:access_token未定义:所以我需要保存生成的令牌并在我所有的 API 测试

const API_STAGING_URL = Cypress.env('API_STAGING_URL')

describe('Decathlon API tests', () => {
it('Get token',function(){
cy.request({
  method:'POST',
  url: 'https://test.com/as/token.oauth2?grant_type=client_credentials',
  headers:{
    authorization : 'Basic 1aFJueHkxddsvdvsdcd3cSA=='
  }}).then((response)=>{
    expect(response.status).to.eq(200)
    const access_token = response.body.access_token
    cy.log(access_token)
    cy.log(this.access_token)
  })
  cy.log(this.access_token)
}),

it('Create Cart',function(){      
cy.request({
  method:'POST',
  url: `${API_STAGING_URL}`+"/api/v1/cart",
  headers:{
    Authorization : 'Bearer ' + access_token,
    "Content-Type": 'application/json',
    "Cache-Control": 'no-cache',
    "User-Agent": 'PostmanRuntime/7.29.2',
    "Accept": '*/*',
    "Accept-Encoding": 'gzip, deflate, br',
    "Connection": 'keep-alive',
    "Postman-Token": '<calculated when request is sent>'

  },
      
            
  }}).then((response)=>{
    //Get statut 200
    expect(response.status).to.eq(200)
    //Get property headers
    
  })})
  
})
google-chrome automated-tests cypress
3个回答
0
投票

这是一个范围问题 -

access_token
不存在于创建它的块之外。 Filip Hric 有一篇很棒的博客文章,介绍了在 Cypress 中使用变量。我最喜欢的策略是将值存储在 Cypress 环境变量中。

const API_STAGING_URL = Cypress.env('API_STAGING_URL');

describe('Decathlon API tests', () => {
  it('Get token', function () {
    cy.request({
      method: 'POST',
      url: 'https://test.com/as/token.oauth2?grant_type=client_credentials',
      headers: {
        authorization: 'Basic 1aFJueHkxddsvdvsdcd3cSA=='
      }
    }).then((response) => {
      expect(response.status).to.eq(200);
      Cypress.env('access_token', response.body.access_token);
      cy.log(Cypress.env('access_token'));
    });
  });

  it('Create Cart', function () {
    cy.request({
      method: 'POST',
      url: `${API_STAGING_URL}` + '/api/v1/cart',
      headers: {
        Authorization: `Bearer ${Cypress.env('access_token')}`,
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache',
        'User-Agent': 'PostmanRuntime/7.29.2',
        Accept: '*/*',
        'Accept-Encoding': 'gzip, deflate, br',
        Connection: 'keep-alive',
        'Postman-Token': '<calculated when request is sent>'
      }
    }).then((response) => {
      // Get statut 200
      expect(response.status).to.eq(200);
      // Get property headers
    });
  });
});

0
投票

另一种方法是在钩子中创建 access_token,然后您可以在 it() 块中访问它。

有几种方法可以做到。

使用变量:

let text
beforeEach(() => {
  cy.wrap(null).then(() => {
    text = "Hello"
  })
})

it("should have text 'Hello'", function() {
  // can access text variable directly
  cy.wrap(text).should('eq', 'Hello')
})

使用别名:

beforeEach(() => {
  cy.wrap(4).as("Number")
})

it("should log number", function() {
  // can access alias with function() and this keyword
  cy.wrap(this.Number).should('eq', 4)
})

这是一个工作示例


0
投票

由于您已使用

function()
定义测试回调,因此您可以在
this
范围内传递令牌。

describe('Decathlon API tests', () => {

  it('gets the token', function() {
    cy.request(...)
      .then(response => {
        this.token = response.body.access_token
      })
  })

  it('uses the token', function() { 
    
    expect(this.token).not.to.be.undefined   // ✅ passes

    cy.request({
      ...
      headers:{
        Authorization : 'Bearer ' + this.token,
        ...
      },
    })
    .then(response => {
      ...

请注意,您必须保持在同一域中才能进行这两项测试。

如果您想以稳定的方式保存跨测试的数据,请使用插件 cypress-data-session

© www.soinside.com 2019 - 2024. All rights reserved.