It’s pretty likely that we’ll need to login as a particular user for many tests, let’s take our cy.request command and turn it into a custom command to make it easier for the places we’ll be needing a logged in user.
commands.js:
Cypress.Commands.add('createUser', overrides => { const user = buildUser(overrides) cy.request({ url: 'http://localhost:3000/register', method: 'POST', body: user, }).then(response => ({...response.body.user, ...user})) }) Cypress.Commands.add('login', user => { return cy .request({ url: 'http://localhost:3000/login', method: 'POST', body: user, }) .then(response => { window.localStorage.setItem('token', response.body.user.token) return {...response.body.user, ...user} }) }) Cypress.Commands.add('loginAsNewUser', () => { cy.createUser().then(user => { cy.login(user) }) })
spec.js:
describe('authenticated calculator', () => { it('displays the username', () => { cy.loginAsNewUser().then(user => { cy.visit('/') .findByTestId('username-display') .should('have.text', user.username) .findByText(/logout/i) .click() .findByTestId('username-display') .should('not.exist') }) }) })