Preserve cookies / localStorage session across tests in Cypress

前端 未结 6 797
抹茶落季
抹茶落季 2020-12-30 21:58

I want to save/persist/preserve a cookie or localStorage token that is set by a cy.request(), so that I don\'t have to use a custom command to login on ever

6条回答
  •  猫巷女王i
    2020-12-30 22:04

    You can add your own login command to Cypress, and use the cypress-localstorage-commands package to persist localStorage between tests.

    In support/commands:

    import "cypress-localstorage-commands";
    
    Cypress.Commands.add('loginAs', (UserEmail, UserPwd) => {
      cy.request({
        method: 'POST',
        url: "/loginWithToken",
        body: {
          user: {
            email: UserEmail,
            password: UserPwd,
          }
        }
      })
        .its('body')
        .then((body) => {
          cy.setLocalStorage("accessToken", body.accessToken);
          cy.setLocalStorage("refreshToken", body.refreshToken);
        });
    });
    

    Inside your tests:

    describe("when user FOO is logged in", ()=> {
      before(() => {
        cy.loginAs("foo@foo.com", "fooPassword");
        cy.saveLocalStorage();
      });
    
      beforeEach(() => {
        cy.visit("/your-private-page");
        cy.restoreLocalStorage();
      });
    
      it('should exist accessToken in localStorage', () => {
        cy.getLocalStorage("accessToken").should("exist");
      });
    
      it('should exist refreshToken in localStorage', () => {
        cy.getLocalStorage("refreshToken").should("exist");
      });
    });
    

提交回复
热议问题