In Cypress, set a token in localStorage before test

空扰寡人 提交于 2019-12-20 10:00:56

问题


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 Cypress Documentation?


回答1:


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()
})



回答2:


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();
});



回答3:


I have spent so many hours on this and finally I can safely conclude that it will never work for OAuth requests.

It may work for local server but not when you getting token for authentication.



来源:https://stackoverflow.com/questions/50820732/in-cypress-set-a-token-in-localstorage-before-test

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!