In Cypress, set a token in localStorage before test
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: '[email protected]',
password: 'jakejake',
}
}
})
.then((resp) => {
window.localStorage.setItem('jwt', resp.body.user.token)
})
})
Then in your test:
beforeEach(() => {
cy.login()
})
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: '[email protected]',
password: 'jakejake',
}
}
})
.its('body')
.then(body => {
cy.setLocalStorage("jwt", body.user.token);
})
});
Then, in your tests:
before(() => {
cy.login();
cy.saveLocalStorage();
});
beforeEach(() => {
cy.restoreLocalStorage();
});