In Cypress, set a token in localStorage before test

后端 未结 5 2017
滥情空心
滥情空心 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:18

    Here's an example of adding a command cy.login() that you can use in any Cypress test, or put in a beforeEach hook.

    Cypress.Commands.add('login', () => { 
      cy.request({
        method: 'POST',
        url: 'http://localhost:3000/api/users/login',
        body: {
          user: {
            email: 'jake@jake.jake',
            password: 'jakejake',
          }
        }
      })
      .then((resp) => {
        window.localStorage.setItem('jwt', resp.body.user.token)
      })
    
    })
    

    Then in your test:

    beforeEach(() => {
      cy.login()
    })
    

提交回复
热议问题