⚪ ️ 3.8 Speed-up E2E tests by reusing login credentials

:white_check_mark: Do: In E2E tests that involve a real backend and rely on a valid user token for API calls, it doesn’t payoff to isolate the test to a level where a user is created and logged-in in every request. Instead, login only once before the tests execution start (i.e. before-all hook), save the token in some local storage and reuse it across requests. This seem to violate one of the core testing principle - keep the test autonomous without resources coupling. While this is a valid worry, in E2E tests performance is a key concern and creating 1-3 API requests before starting each individual tests might lead to horrible execution time. Reusing credentials doesn’t mean the tests have to act on the same user records - if relying on user records (e.g. test user payments history) than make sure to generate those records as part of the test and avoid sharing their existence with other tests. Also remember that the backend can be faked - if your tests are focused on the frontend it might be better to isolate it and stub the backend API (see bullet 3.6).


Otherwise: Given 200 test cases and assuming login=100ms = 20 seconds only for logging-in again and again


Code Examples

:clap: Doing It Right Example: Logging-in before-all and not before-each

let authenticationToken;
 
// happens before ALL tests run
before(() => {
  cy.request('POST', 'http://localhost:3000/login', {
    username: Cypress.env('username'),
    password: Cypress.env('password'),
  })
  .its('body')
  .then((responseFromLogin) => {
    authenticationToken = responseFromLogin.token;
  })
})
 
// happens before EACH test
beforeEach(setUser => {
  cy.visit('/home', () => {
    onBeforeLoad (win => {
      win.localStorage.setItem('token', JSON.stringify(authenticationToken))
    })
  })
})