Cypress如何从localstorage返回JWT令牌并在另一个api调用中使用它
嗨,我想做的是将localStorage保存到某个地方,这样我可以在不同的测试场景中引用它,但我不确定这是否可行,因为我的token1变量总是空的 这是我的support/command.js文件Cypress如何从localstorage返回JWT令牌并在另一个api调用中使用它,jwt,token,cypress,Jwt,Token,Cypress,嗨,我想做的是将localStorage保存到某个地方,这样我可以在不同的测试场景中引用它,但我不确定这是否可行,因为我的token1变量总是空的 这是我的support/command.js文件 Cypress.Commands.add('postTokenLogin', () => { cy.request({ method: 'POST', url: '***/people/sign_in', body: {
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')
})
})
})
我可以再要一个it('GET colors',()=>{})并只传递令牌1吗?您正在异步代码中工作,因此如果需要使用令牌而不是验证,您应该像下面那样嵌套代码
导入“cypress localstorage命令”;
让token1='';
描述('HTTP示例',()=>{
之前(()=>{
cy.postTokenLogin();
cy.saveLocalStorage();
});
在每个之前(()=>{
恢复性存储();
});
它(“JWT令牌的值应该存在于localStorage中”,()=>{
cy.getLocalStorage('token')。然后(token=>{
cy.log(“token”,token);//我在这里得到了JWT token
});
});
它('获取列表',()=>{
cy.getLocalStorage('token')。然后((token)=>{
令牌1=令牌;
cy.log('Let Tokennn is===>',token1)//始终为空
赛义德请求({
方法:“GET”,
url:“***/peopleList”,
标题:{
“内容类型”:“应用程序/json”,
“授权”:令牌1/=>这也是空的
}
})。然后((响应)=>{
expect(response.body).have.property('firstName'))
expect(response.body).have.property('lastname'))
})
})
})
感谢您的回复。我如何将该令牌存储在某个地方,以便在其他任何地方使用?将其转储到文件中,然后再次读取'cy.writeFile('path/to/token.txt','tokenvalue')cy.readFile('path/to/token.txt')。然后((token)=>{……}`@RahulL谢谢您的回答,这正是我想要的答案