问题
Any idea why the 'token' set in localStorage is removed during cypress test run ? 
I have 'loadToken()' function written in commands.js file, while running the test i could see the token is being set, but as soon as cy.visit('/dashboard') is called, the token gets removed/disappeared and still displays the login page and doesnt allow to login. The same way was working with some other projects. 
note: When we actually hit the baseUrl [https://some-url.net] it actually add following extension to url '/auth/login'
Cypress.Commands.add('loadTokens', () => {
    return cy.fixture('tokenData.json').then(data => {
        const keys = Object.keys(data);
        keys.forEach(key => {
            window.localStorage.setItem(key, data[key]);
        });
    });
});
I am calling the loadTokens() and loginRequest() inside before each; 
context('Login and Logout test',()=>{
before(()=>{
cy.visit('/');
})
beforeEach(() => {
cy.loadTokens();
cy.loginRequest();
})
it.only('Check whether the login is possible',()=>{
    cy.viewport(1600, 1000); 
    cy.get('#offCanvasLeft > ul > li > a > span').eq(1).invoke('text').then((text)=>{
        expect(text).to.equal("Dashboard");
    }) 
})
})
Cypress.Commands.add('loginRequest', () => {
  const accessToken = localStorage.getItem('tokens');
    var cookieValue = document.cookie.split(';');
    cy.request({
      method: 'GET',
      url: baseUrl+`/dashboard`,
      headers: {
        'content-type': 'text/html',
        'tokens': `${accessToken}`,
        'cookie': `${cookieValue}`
      }
    })
  })
//cypress.json file:
{
  "baseUrl": "https://some-url.net",
  "numTestsKeptInMemory": 3,
  "chromeWebSecurity": false
}
//Before the cypress test hit the cy.visit() command, I am able to see the tokens set.
回答1:
This Cypess example recipe shows a slightly different pattern for using tokens in local storage and cy.visit().
// but set the user before visiting the page
// so the app thinks it is already authenticated
beforeEach(function setUser () {
  cy.visit('/', {
    onBeforeLoad (win) {
      // and before the page finishes loading
      // set the user object in local storage
      win.localStorage.setItem('user', JSON.stringify(user))
    },
  })
  // the page should be opened and the user should be logged in
})
I presume the onBeforeLoad() callback is used to overcome the problem you are experiencing where cy.visit() clears down local storage.
So, your code would be something like this
beforeEach(function setTokensAndVisit () {
  cy.fixture('tokenData.json').then(tokenData => {
    cy.visit('/dashboard', {
      onBeforeLoad (win) {
        // Set cookie or load localStorage with tokenData here,
        // depending on how your app checks that user is authorized.
        // In a SPA app, this check is likely to done in the router
      },
    })
  })
})
来源:https://stackoverflow.com/questions/60880864/token-set-gets-removed-while-running-the-cypress-test