Reputation: 356
Hi What I am trying to do is to save the localStorage in to variable somewhere , So i can refer to it in different test scenario but I am not sure if that is possible as my token1 variable is always empty.
this is my support/command.js file
Cypress.Commands.add('postTokenLogin', () => {
cy.request({
method: 'POST',
url: '***/people/sign_in',
body: {
"login": "[email protected]",
"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 )
})
})
now in my test case I wanna be able to use that token inside my header
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')
})
})
})
Can I have another it('GET colours ', ()=>{}) and just pass the token1?
Upvotes: 2
Views: 5690
Reputation: 146500
You are working in a async code, so if you need to use the token instead of validation, you should nest the code like below
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')
})
})
})
Upvotes: 1