In Cypress, set a token in localStorage before test

后端 未结 5 2019
滥情空心
滥情空心 2021-01-31 15:35

I want to login and set a localStorage token on the client (specifically jwt)

How can I accomplish this using cy.request, as suggested in the C

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-31 16:10

    As an extra, you can also use the cypress-localstorage-commands package to persist localStorage between tests, so login request will be made only once:

    In support/commands.js:

    import "cypress-localstorage-commands";
    
    Cypress.Commands.add('login', () => { 
      cy.request({
        method: 'POST',
        url: 'http://localhost:3000/api/users/login',
        body: {
          user: {
            email: 'jake@jake.jake',
            password: 'jakejake',
          }
        }
      })
      .its('body')
      .then(body => {
        cy.setLocalStorage("jwt", body.user.token);
      })
    });
    

    Then, in your tests:

    before(() => {
      cy.login();
      cy.saveLocalStorage();
    });
    
    beforeEach(() => {
      cy.restoreLocalStorage();
    });
    

提交回复
热议问题