https://cypress.io logo
also what would you suggest whether using localSto...
# general-chat
m
also what would you suggest whether using localStorage or env variable to store API key got runtime?
d
Hi, why don't you write a custom command to get a token via an API request, extract the token from the response body and save it as an environment variable? Something like this:
Copy code
Cypress.Commands.add('getAccessToken', () => {
  cy.request({
    method: 'POST',
    url: '/api/auth/login',
    body: {
      username: 'testuser',
      password: 'password123'
    }
  }).then((response) => {
    const accessToken = response.body.accessToken;
    Cypress.env('ACCESS_TOKEN', accessToken);
  });
});
And then calling this command, extract this token from the env and use it in other API requests:
m
that is an option. I'm using almost the same with localStorage.
Copy code
cy.setLocalStorage("accessToken", body.access_token);
just would like to know if env var or localStorage is better options in some perspective
d
For example: `it('should get user profile with access token', () => { cy.getAccessToken(); cy.request({ method: 'GET', url: '/api/user/profile', headers: { Authorization:
Bearer ${Cypress.env('ACCESS_TOKEN')}
} }).then((response) => { // test user profile response }); });`
m
as I found localStorage is a bit more difficult to manipulate as when reading it gives a promise back so can't input its value like it gave back the bare value
Copy code
cy.getLocalStorage('access_token').then((token) => {
                cy.deployAssembly(url, token, id);
              })
like env var was used
Copy code
cy.deployAssembly(url, Cyrpress.env('access_token'), id);
d
Probably there is a more elegant way besides these two. when comparing these two, in general, it is recommended to use env over localStorage for storing variables in tests as more secure and flexible way. Moreover, localStorage data can be cleared or reset by user.
m
you mean using env var is a more elegant way over localStorage?
d
no, maybe something other than both ways
And agree, asynchronous execution can leave its negative imprint..