首页 > 解决方案 > 赛普拉斯如何从本地存储返回 JWT 令牌并在另一个 api 调用中使用它

问题描述

嗨,我想做的是将 localStorage 保存到某个地方的变量中,因此我可以在不同的测试场景中引用它,但我不确定这是否可行,因为我的 token1 变量始终为空。

这是我的 support/command.js 文件

Cypress.Commands.add('postTokenLogin', () => {
    cy.request({
        method: 'POST',
        url: '***/people/sign_in',
        body: {
            "login": "test@test.com",
            "password":"***",     
        },
        headers:{
            'content-type': 'application/json'
        }
    }).then((response) => {
        expect(response.body).have.property('firstName')
        expect(response.body.token).have.property('authorization')
        cy.setLocalStorage('token',response.body.token.authorization )
    })
})

现在在我的测试用例中,我希望能够在我的标题中使用该令牌

import "cypress-localstorage-commands";
    let token1 = '';
    describe('HTTP Example', ()=>{
        before(() => {
            cy.postTokenLogin();
            cy.saveLocalStorage();
          });
        beforeEach(() => {
            cy.restoreLocalStorage();
          });

        it("the value of JWT Token should exist in localStorage", () => {
            cy.getLocalStorage('token').then(token => {
              cy.log("the token", token); // I get JWT Token in here
            });
          });
        it('GET List ', ()=>{
            
            cy.getLocalStorage('token').then((token) => {
                token1 = token;
              })
              cy.log('Let Tokennn is ===>' , token1) // Always Empty
cy.request({
    method: 'GET',
    url: '***/peopleList',
    headers:{
        'content-type': 'application/json',
         'Authorization': token1 // ===> this is also empty
    }
}).then((response) => {
    expect(response.body).have.property('firstName')
    expect(response.body).have.property('lastname')
})
        })
    })

我可以再有一个它('GET colors', ()=>{}) 并传递 token1 吗?

标签: jwttokencypress

解决方案


您正在使用异步代码,因此如果您需要使用令牌而不是验证,您应该嵌套如下代码

import "cypress-localstorage-commands";
let token1 = '';
describe('HTTP Example', () => {
      before(() => {
        cy.postTokenLogin();
        cy.saveLocalStorage();
      });
      beforeEach(() => {
        cy.restoreLocalStorage();
      });

      it("the value of JWT Token should exist in localStorage", () => {
        cy.getLocalStorage('token').then(token => {
          cy.log("the token", token); // I get JWT Token in here
        });
      });
      it('GET List ', () => {

        cy.getLocalStorage('token').then((token) => {
          token1 = token;
          cy.log('Let Tokennn is ===>', token1) // Always Empty

          cy.request({
            method: 'GET',
            url: '***/peopleList',
            headers: {
              'content-type': 'application/json',
              'Authorization': token1 // ===> this is also empty
            }
          }).then((response) => {
            expect(response.body).have.property('firstName')
            expect(response.body).have.property('lastname')
          })
        })

      })

推荐阅读