Exit course
Chapter 6 of 11 Beginner 6 min read 3 quick checks Updated

Custom Commands and Logging In Once with cy.session

Watch this chapter Starts at 3:40 in the 9:03 course video.
On this page
  1. A first custom command
  2. Why logging in needs special treatment
  3. A cy.login command built on cy.session
  4. Faster still: log in without the form

Sooner or later every suite repeats the same steps in many tests, and the most expensive repeated step is logging in. This chapter turns repeated steps into custom commands, then makes login fast with cy.session(), which caches a logged-in browser state and restores it for each test.

A first custom command#

Custom commands live in cypress/support/commands.js, which cypress/support/e2e.js imports before every spec. Add one:

Cypress.Commands.add('addTodo', (text) => {
  cy.get('[data-test=new-todo]').type(`${text}{enter}`)
})

and use it like a built-in command:

describe('custom commands', () => {
  beforeEach(() => {
    cy.visit('/todo')
  })

  it('adds two todos with cy.addTodo', () => {
    cy.addTodo('Buy milk')
    cy.addTodo('Pay rent')

    cy.get('.todo-list li').should('have.length', 4)
  })
})

The commands inside are queued like any others, so a custom command needs no return and no await.

When should something be a custom command? A good test is whether the name describes a user intention ("add a todo", "log in as admin") rather than a mechanical step. Commands that wrap a single cy.get with a different name add indirection without adding meaning. For grouping many steps about one page, plain JavaScript functions or modules work just as well; Cypress does not require page objects, and our page object model course covers when they help.

You add Cypress.Commands.add('addTodo', ...) to a new file cypress/support/todo-commands.js. Every spec now fails with "cy.addTodo is not a function". What is missing?

Only the support file runs automatically before each spec. Any other file has to be imported from it, the same way the scaffolded e2e.js imports commands.js.

Why logging in needs special treatment#

Test isolation (chapter 1) clears cookies, localStorage and sessionStorage before every test. That is what keeps tests independent, but it also logs you out before every test. Logging in through the form each time works, and is slow: a suite with 200 tests fills in the login form 200 times.

cy.session(id, setup, options) solves this:

  • The first time it runs with a given id, it clears the browser, runs your setup function, and saves the resulting cookies, localStorage and sessionStorage.
  • Every later time in the same spec, it skips setup and restores the saved state.
  • If you pass a validate function, it runs after every create and restore; if validation fails, the session is rebuilt from scratch.

A cy.login command built on cy.session#

The login form at the-internet.herokuapp.com/login accepts tomsmith / SuperSecretPassword! and sets a rack.session cookie. Add this to cypress/support/commands.js:

Cypress.Commands.add('login', (username, password) => {
  cy.session(
    username,
    () => {
      cy.visit('https://the-internet.herokuapp.com/login')
      cy.get('#username').type(username)
      cy.get('#password').type(password, { log: false })
      cy.get('button[type=submit]').click()
      cy.contains('#flash', 'You logged into a secure area!')
    },
    {
      validate() {
        cy.getCookie('rack.session').should('exist')
      },
    },
  )
})

Things to notice:

  • The id is the username, so logging in as two different users keeps two separate cached sessions.
  • The setup function ends with an assertion that the login worked. Without it, cy.session would happily cache whatever state existed right after the click, possibly before the cookie was set.
  • { log: false } keeps the password out of the command log, screenshots and videos.
  • validate checks the cookie is still there. A real application might instead call an endpoint that returns the current user with cy.request and check the status.

Then use it in cypress/e2e/secure.cy.js:

describe('secure area', () => {
  beforeEach(() => {
    cy.login(Cypress.env('username'), Cypress.env('password'))
    cy.visit('https://the-internet.herokuapp.com/secure')
  })

  it('shows the secure area heading', () => {
    cy.get('h2').should('contain', 'Secure Area')
  })

  it('has a logout button', () => {
    cy.contains('a', 'Logout').should('have.attr', 'href', '/logout')
  })
})

The credentials come from Cypress.env(), which chapter 6 sets up; for now, create cypress.env.json in the project root:

{
  "username": "tomsmith",
  "password": "SuperSecretPassword!"
}

and add it to .gitignore, since in a real project it holds real secrets.

Run the spec in npx cypress open and expand the session entry in the command log. The first test shows the session being created; the second shows it restored, without the login form. Note that cy.session leaves you on a blank page, which is why beforeEach visits the secure page afterwards.

Some tests in a spec fail with "not logged in" even though cy.login() runs in beforeEach. The setup function ends with cy.get('button[type=submit]').click(). What is the most likely cause?

Cypress saves the state as soon as the setup's commands finish. Ending the setup with an assertion that the login completed (a success message, a URL, a cookie) makes it wait for the real logged-in state. A validate function then catches a bad cache.

Faster still: log in without the form#

The setup above still drives the login form once per spec. If your application has a login API, call it with cy.request() inside the setup instead (chapter 4), and store whatever the response gives you the way the app does: a cookie is kept automatically, a token usually goes into localStorage. Even the first login then skips the UI. The cy.session documentation has examples for both. Keep one test that logs in through the real form, so the form itself is still covered.

By default a session is cached per spec file. Passing cacheAcrossSpecs: true in the options shares it across all specs of the same run on the same machine, which helps large suites that log in as the same user everywhere.

Your tests log in as either "admin" or "viewer". With cy.session(username, ...), what happens when a spec switches from an admin test to a viewer test?

The id identifies the cached session. Different ids are different sessions, and cy.session clears the browser before restoring the requested one, so nothing leaks from admin into viewer.