首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Cypress:跨多个API测试重用auth令牌

Cypress:跨多个API测试重用auth令牌
EN

Stack Overflow用户
提问于 2019-11-23 14:19:01
回答 3查看 18.2K关注 0票数 11

我有一个Rest,它生成一个令牌。此会话令牌跨多个REST作为授权标记使用。我使用这个作为参考:jwt/cypress/integration/spec.js

但是,在该示例中,生成令牌的函数嵌入到测试中。我试图创建一个应该在本地存储的自定义命令,但是测试没有对它进行检测。注意,自定义命令中没有包含任何返回值。

我在support/commands.js下面的代码

代码语言:javascript
运行
复制
let identity
Cypress.Commands.add('postToken', () => {
    cy.request({
        method: 'POST',
        url: Cypress.env('api_identity_url'), //get from cypress.env.json
        form: true, //sets to application/x-www-form-urlencoded
        body: {
            grant_type: 'client_credentials',
            scope: 'xero_all-apis'
        },
        auth: {
            username: Cypress.env('api_identity_username'),
            password: Cypress.env('api_identity_password')
        }
    })
        .its('body')
        .then((response) => {
            identity = response
            window.localStorage.setItem('identity', JSON.stringify(identity))
            cy.log(identity.access_token)
        })
})

我的测试

代码语言:javascript
运行
复制
context('Check token details', () => {
  it('Check token', () => {
      cy.postToken()
      const bToken = window.localStorage.getItem('identity')
      cy.log(bToken)
  })
})

当我运行测试时,日志显示“identity”的null值。但是,它显示了自定义命令中的当前值,我尝试使用cy.log(identity.access_token)使用cy.writeFile,但我认为这不是一个干净的方法。必须有某种方式可以在函数和不同类之间传递数据。

示例JSON格式:

代码语言:javascript
运行
复制
{
  "token": "<this is the value I would like to use for other API's authorisation bearer token>",
  "expires_in": 1200,
  "token_type": "Bearer"
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-11-24 10:23:11

您可以使用cypress.本地存储.命令包在测试之间持久化localStorage。

support/commands.js

代码语言:javascript
运行
复制
import "cypress-localstorage-commands";

Cypress.Commands.add('postToken', () => {
  cy.request({
    method: 'POST',
    url: Cypress.env('api_identity_url'), //get from cypress.env.json
    form: true, //sets to application/x-www-form-urlencoded
    body: {
      grant_type: 'client_credentials',
      scope: 'xero_all-apis'
    },
    auth: {
      username: Cypress.env('api_identity_username'),
      password: Cypress.env('api_identity_password')
    }
  })
  .its('body')
  .then(identity => {
    cy.setLocalStorage("identity_token", identity.token);
  });
});

在你的测试中:

代码语言:javascript
运行
复制
describe("postToken", ()=> {
  before(() => {
    cy.postToken();
    cy.saveLocalStorage();
  });

  beforeEach(() => {
    cy.restoreLocalStorage();
  });

  it("should exist identity in localStorage", () => {
    cy.getLocalStorage("identity_token").should("exist");
    cy.getLocalStorage("identity_token").then(token => {
      console.log("Identity token", token);
    });
  });

  it("should still exist identity in localStorage", () => {
    cy.getLocalStorage("identity_token").should("exist");
    cy.getLocalStorage("identity_token").then(token => {
      console.log("Identity token", token);
    });
  });
});
票数 13
EN

Stack Overflow用户

发布于 2019-11-29 11:46:28

谢谢哈维尔给我看了cypress-localstorage-commands的包裹。我开始使用它。在此之前,我通常会得到这样的登录令牌。

代码语言:javascript
运行
复制
describe('Record audit', () => {
    let token = null;

    before(() => {
        cy.login().then((responseToken) => { // or postToken() in your case
            token = responseToken;
        });
    });

    it('I can use the token here', () => {
        cy.log(token);
    });
});

唯一的区别是我的login命令返回令牌。代码中应该是这样的

代码语言:javascript
运行
复制
// commands.js

.then((response) => {
    identity = response
    window.localStorage.setItem('identity', JSON.stringify(identity))
    cy.log(identity.access_token)
    return identity.access_token
})
票数 0
EN

Stack Overflow用户

发布于 2020-11-27 23:01:04

我在commmand.js中使用了这段代码

代码语言:javascript
运行
复制
var headers_login = new Headers()
headers_login.append('Content-Type', 'application/json')

Cypress.Commands.add('get_token', (username, password)=>{
var token = ""
cy.request({
    method: 'POST',
    url: Cypress.env("api") + "users/getToken",
    failOnStatusCode: false,
    json: true,
    form: true,
    body: {username: username, password: password},
    headers: headers_login
 }).then((json) => {
    //cy.setLocalStorage('token', json.body.response.data.token)   
    token = json.body.response.data.token
    return token;
 }) }) 

在测试中添加以下代码

代码语言:javascript
运行
复制
describe('test', ()=>{
 before(()=>{
    cy.get_token('username', 'password').then(youToken => {
        cy.visit('/', {
             onBeforeLoad: function (window) {
                window.localStorage.setItem('token', youToken);
             }
         })
     }) 
     cy.close_welcome()        
 })
 it('test 001', ()=>{
       // contain test 
 })})
afterEach(()=>{cy.clearLocalStorage('token')})
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59008563

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档